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
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/presenter/BasePresenter.java
// Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java // public class BaseApplication extends Application { // public static BaiDuApiService mBaiDuApiService; // public static AppComponent mAppComponent; // private static Application mApplication; // // public static AppComponent getAppComponent() { // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // return mAppComponent; // } // // public static Context getContext() { // return mApplication; // } // // @Override // public void onCreate() { // super.onCreate(); // setupLogUtils(); // setupComponent(); // mApplication = this; // MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); // } // // /** // * 设置LogUtil // */ // private void setupLogUtils() { // LogUtils.getLogConfig() // .configAllowLog(true) // .configTagPrefix("TouchNews") // .configShowBorders(true) // .configLevel(LogLevel.TYPE_VERBOSE); // } // // /** // * 设置AppComponent // */ // private void setupComponent() { // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // }
import com.github.cchao.touchnews.BaseApplication; import com.github.cchao.touchnews.util.BaiDuApiService;
package com.github.cchao.touchnews.presenter; /** * Created by cchao on 2016/8/18. * E-mail: cchao1024@163.com * Description: 根 Presenter 绑定View */ public abstract class BasePresenter<V> { BaiDuApiService mBaiDBaiDuApiService; V mView; public BasePresenter() {
// Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java // public class BaseApplication extends Application { // public static BaiDuApiService mBaiDuApiService; // public static AppComponent mAppComponent; // private static Application mApplication; // // public static AppComponent getAppComponent() { // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // return mAppComponent; // } // // public static Context getContext() { // return mApplication; // } // // @Override // public void onCreate() { // super.onCreate(); // setupLogUtils(); // setupComponent(); // mApplication = this; // MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); // } // // /** // * 设置LogUtil // */ // private void setupLogUtils() { // LogUtils.getLogConfig() // .configAllowLog(true) // .configTagPrefix("TouchNews") // .configShowBorders(true) // .configLevel(LogLevel.TYPE_VERBOSE); // } // // /** // * 设置AppComponent // */ // private void setupComponent() { // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // Path: app/src/main/java/com/github/cchao/touchnews/presenter/BasePresenter.java import com.github.cchao.touchnews.BaseApplication; import com.github.cchao.touchnews.util.BaiDuApiService; package com.github.cchao.touchnews.presenter; /** * Created by cchao on 2016/8/18. * E-mail: cchao1024@163.com * Description: 根 Presenter 绑定View */ public abstract class BasePresenter<V> { BaiDuApiService mBaiDBaiDuApiService; V mView; public BasePresenter() {
mBaiDBaiDuApiService = BaseApplication.getAppComponent().getBaiDuApiService();
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/BaseApplication.java
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // }
import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent;
package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService;
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent; package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService;
public static AppComponent mAppComponent;
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/BaseApplication.java
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // }
import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent;
package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService; public static AppComponent mAppComponent; private static Application mApplication; public static AppComponent getAppComponent() { mBaiDuApiService = mAppComponent.getBaiDuApiService(); return mAppComponent; } public static Context getContext() { return mApplication; } @Override public void onCreate() { super.onCreate(); setupLogUtils(); setupComponent(); mApplication = this; MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); } /** * 设置LogUtil */ private void setupLogUtils() { LogUtils.getLogConfig() .configAllowLog(true) .configTagPrefix("TouchNews") .configShowBorders(true) .configLevel(LogLevel.TYPE_VERBOSE); } /** * 设置AppComponent */ private void setupComponent() { mAppComponent = DaggerAppComponent.builder()
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent; package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService; public static AppComponent mAppComponent; private static Application mApplication; public static AppComponent getAppComponent() { mBaiDuApiService = mAppComponent.getBaiDuApiService(); return mAppComponent; } public static Context getContext() { return mApplication; } @Override public void onCreate() { super.onCreate(); setupLogUtils(); setupComponent(); mApplication = this; MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); } /** * 设置LogUtil */ private void setupLogUtils() { LogUtils.getLogConfig() .configAllowLog(true) .configTagPrefix("TouchNews") .configShowBorders(true) .configLevel(LogLevel.TYPE_VERBOSE); } /** * 设置AppComponent */ private void setupComponent() { mAppComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/BaseApplication.java
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // }
import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent;
package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService; public static AppComponent mAppComponent; private static Application mApplication; public static AppComponent getAppComponent() { mBaiDuApiService = mAppComponent.getBaiDuApiService(); return mAppComponent; } public static Context getContext() { return mApplication; } @Override public void onCreate() { super.onCreate(); setupLogUtils(); setupComponent(); mApplication = this; MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); } /** * 设置LogUtil */ private void setupLogUtils() { LogUtils.getLogConfig() .configAllowLog(true) .configTagPrefix("TouchNews") .configShowBorders(true) .configLevel(LogLevel.TYPE_VERBOSE); } /** * 设置AppComponent */ private void setupComponent() { mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this))
// Path: app/src/main/java/com/github/cchao/touchnews/di/component/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class}) // public interface AppComponent { // BaiDuApiService getBaiDuApiService(); // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java // @Module // public class ApiModule { // /** // * @param baseUrl baseUrl // * @return Retrofit 对象 // */ // private Retrofit getApiService(@NonNull String baseUrl) { // return new Retrofit.Builder() // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .baseUrl(baseUrl) // .build(); // } // // /** // * @return 百度的api接口 // */ // @Singleton // @Provides // protected BaiDuApiService provideBaiDuApiService() { // return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/di/module/AppModule.java // @Module // public final class AppModule { // // private Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // public Application provideApplication() { // return application; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java import android.app.Application; import android.content.Context; import android.content.res.Configuration; import com.apkfuns.logutils.LogLevel; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.di.component.AppComponent; import com.github.cchao.touchnews.di.component.DaggerAppComponent; import com.github.cchao.touchnews.di.module.ApiModule; import com.github.cchao.touchnews.di.module.AppModule; import com.github.cchao.touchnews.util.BaiDuApiService; import com.umeng.analytics.MobclickAgent; package com.github.cchao.touchnews; /** * * Created by H on 2016/3/12. */ public class BaseApplication extends Application { public static BaiDuApiService mBaiDuApiService; public static AppComponent mAppComponent; private static Application mApplication; public static AppComponent getAppComponent() { mBaiDuApiService = mAppComponent.getBaiDuApiService(); return mAppComponent; } public static Context getContext() { return mApplication; } @Override public void onCreate() { super.onCreate(); setupLogUtils(); setupComponent(); mApplication = this; MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); } /** * 设置LogUtil */ private void setupLogUtils() { LogUtils.getLogConfig() .configAllowLog(true) .configTagPrefix("TouchNews") .configShowBorders(true) .configLevel(LogLevel.TYPE_VERBOSE); } /** * 设置AppComponent */ private void setupComponent() { mAppComponent = DaggerAppComponent.builder() .appModule(new AppModule(this))
.apiModule(new ApiModule())
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/widget/VaryViewWidget.java
// Path: app/src/main/java/com/github/cchao/touchnews/util/Constant.java // public class Constant { // /** // * 显示提示信息给用户 e.g. 没有网络、正在加载、异常 // * // * @see // */ // public enum INFO_TYPE { // NO_NET, ALERT, LOADING, EMPTY, ORIGIN // } // // }
import android.view.View; import android.view.ViewGroup; import com.github.cchao.touchnews.util.Constant;
} public void setOriginView(View originView) { mOriginView = originView; } public View getLoadingView() { return mLoadingView; } public void setLoadingView(View loadingView) { mLoadingView = loadingView; } public View getNoNetView() { return mNoNetView; } public void setNoNetView(View noNetView) { mNoNetView = noNetView; } public View getEmptyView() { return mEmptyView; } public void setEmptyView(View emptyView) { mEmptyView = emptyView; }
// Path: app/src/main/java/com/github/cchao/touchnews/util/Constant.java // public class Constant { // /** // * 显示提示信息给用户 e.g. 没有网络、正在加载、异常 // * // * @see // */ // public enum INFO_TYPE { // NO_NET, ALERT, LOADING, EMPTY, ORIGIN // } // // } // Path: app/src/main/java/com/github/cchao/touchnews/widget/VaryViewWidget.java import android.view.View; import android.view.ViewGroup; import com.github.cchao.touchnews.util.Constant; } public void setOriginView(View originView) { mOriginView = originView; } public View getLoadingView() { return mLoadingView; } public void setLoadingView(View loadingView) { mLoadingView = loadingView; } public View getNoNetView() { return mNoNetView; } public void setNoNetView(View noNetView) { mNoNetView = noNetView; } public View getEmptyView() { return mEmptyView; } public void setEmptyView(View emptyView) { mEmptyView = emptyView; }
public void showView(Constant.INFO_TYPE INFOType) {
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java
// Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java // public class BaseApplication extends Application { // public static BaiDuApiService mBaiDuApiService; // public static AppComponent mAppComponent; // private static Application mApplication; // // public static AppComponent getAppComponent() { // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // return mAppComponent; // } // // public static Context getContext() { // return mApplication; // } // // @Override // public void onCreate() { // super.onCreate(); // setupLogUtils(); // setupComponent(); // mApplication = this; // MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); // } // // /** // * 设置LogUtil // */ // private void setupLogUtils() { // LogUtils.getLogConfig() // .configAllowLog(true) // .configTagPrefix("TouchNews") // .configShowBorders(true) // .configLevel(LogLevel.TYPE_VERBOSE); // } // // /** // * 设置AppComponent // */ // private void setupComponent() { // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // } // }
import android.annotation.SuppressLint; import android.content.Context; import android.support.annotation.StringRes; import android.view.View; import android.widget.Toast; import com.github.cchao.touchnews.BaseApplication;
package com.github.cchao.touchnews.util; /** * Created by cchao on 2016/4/22. * E-mail: cchao1024@163.com * Description: */ public class ToastUtil { private static Toast toast; private static View view; private ToastUtil() { } @SuppressLint("ShowToast") private static void getToast(Context context) { if (toast == null) { toast = new Toast(context); } if (view == null) { view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); } toast.setView(view); } public static void showShortToast(Context context, CharSequence msg) { if (context == null) {
// Path: app/src/main/java/com/github/cchao/touchnews/BaseApplication.java // public class BaseApplication extends Application { // public static BaiDuApiService mBaiDuApiService; // public static AppComponent mAppComponent; // private static Application mApplication; // // public static AppComponent getAppComponent() { // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // return mAppComponent; // } // // public static Context getContext() { // return mApplication; // } // // @Override // public void onCreate() { // super.onCreate(); // setupLogUtils(); // setupComponent(); // mApplication = this; // MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "5739942de0f55a0b3c001aab", "APP0")); // } // // /** // * 设置LogUtil // */ // private void setupLogUtils() { // LogUtils.getLogConfig() // .configAllowLog(true) // .configTagPrefix("TouchNews") // .configShowBorders(true) // .configLevel(LogLevel.TYPE_VERBOSE); // } // // /** // * 设置AppComponent // */ // private void setupComponent() { // mAppComponent = DaggerAppComponent.builder() // .appModule(new AppModule(this)) // .apiModule(new ApiModule()) // .build(); // mBaiDuApiService = mAppComponent.getBaiDuApiService(); // // } // // @Override // public void onLowMemory() { // super.onLowMemory(); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // } // } // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java import android.annotation.SuppressLint; import android.content.Context; import android.support.annotation.StringRes; import android.view.View; import android.widget.Toast; import com.github.cchao.touchnews.BaseApplication; package com.github.cchao.touchnews.util; /** * Created by cchao on 2016/4/22. * E-mail: cchao1024@163.com * Description: */ public class ToastUtil { private static Toast toast; private static View view; private ToastUtil() { } @SuppressLint("ShowToast") private static void getToast(Context context) { if (toast == null) { toast = new Toast(context); } if (view == null) { view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); } toast.setView(view); } public static void showShortToast(Context context, CharSequence msg) { if (context == null) {
showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/activity/WebActivity.java
// Path: app/src/main/java/com/github/cchao/touchnews/util/Keys.java // public class Keys { // public static final String BAI_DU_KEY = "96a573502b09d771c6431c106d04613a"; // public static final String BAI_DU_API_KEY = "1bb91df70ccde8148a2c3da582ca9ff2"; // public static final String API_KEY = "apikey"; // public static final String KEY = "key"; // public static final String URL = "url"; // public static final String CITY = "city"; // public static final String INFO = "info"; // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/LogUtil.java // public class LogUtil { // public static final boolean DEBUG = true; // // public static void v(String tag, String mess) { // if (DEBUG) { // Log.v(tag, mess); // } // } // // public static void d(String tag, String mess) { // if (DEBUG) { // Log.d(tag, mess); // } // } // // public static void i(String tag, String mess) { // if (DEBUG) { // Log.i(tag, mess); // } // } // // public static void w(String tag, String mess) { // if (DEBUG) { // Log.w(tag, mess); // } // } // // public static void e(String tag, String mess) { // if (DEBUG) { // Log.e(tag, mess); // } // } // // public static void v(String mess) { // if (DEBUG) { // Log.v(getTag(), mess); // } // } // // public static void d(String mess) { // if (DEBUG) { // Log.d(getTag(), mess); // } // } // // public static void i(String mess) { // if (DEBUG) { // Log.i(getTag(), mess); // } // } // // public static void w(String mess) { // if (DEBUG) { // Log.w(getTag(), mess); // } // } // // public static void e(String mess) { // if (DEBUG) { // Log.e(getTag(), mess); // } // } // // private static String getTag() { // StackTraceElement[] trace = new Throwable().fillInStackTrace() // .getStackTrace(); // String callingClass = ""; // for (int i = 2; i < trace.length; i++) { // Class<?> clazz = trace[i].getClass(); // if (!clazz.equals(LogUtil.class)) { // callingClass = trace[i].getClassName(); // callingClass = callingClass.substring(callingClass // .lastIndexOf('.') + 1); // break; // } // } // return callingClass; // } // }
import android.webkit.WebSettings; import android.webkit.WebView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.util.Keys; import com.github.cchao.touchnews.util.LogUtil; import butterknife.Bind;
package com.github.cchao.touchnews.ui.activity; /** * Created by cchao on 2016/8/19. * E-mail: cchao1024@163.com * Description: 网页显示页 */ public class WebActivity extends BaseActivity { @Bind(R.id.webview_article_detail) WebView mWebView; @Override protected int getLayoutID() { return R.layout.activity_web; } @Override protected void initialize() { super.initialize(); setWebView();
// Path: app/src/main/java/com/github/cchao/touchnews/util/Keys.java // public class Keys { // public static final String BAI_DU_KEY = "96a573502b09d771c6431c106d04613a"; // public static final String BAI_DU_API_KEY = "1bb91df70ccde8148a2c3da582ca9ff2"; // public static final String API_KEY = "apikey"; // public static final String KEY = "key"; // public static final String URL = "url"; // public static final String CITY = "city"; // public static final String INFO = "info"; // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/LogUtil.java // public class LogUtil { // public static final boolean DEBUG = true; // // public static void v(String tag, String mess) { // if (DEBUG) { // Log.v(tag, mess); // } // } // // public static void d(String tag, String mess) { // if (DEBUG) { // Log.d(tag, mess); // } // } // // public static void i(String tag, String mess) { // if (DEBUG) { // Log.i(tag, mess); // } // } // // public static void w(String tag, String mess) { // if (DEBUG) { // Log.w(tag, mess); // } // } // // public static void e(String tag, String mess) { // if (DEBUG) { // Log.e(tag, mess); // } // } // // public static void v(String mess) { // if (DEBUG) { // Log.v(getTag(), mess); // } // } // // public static void d(String mess) { // if (DEBUG) { // Log.d(getTag(), mess); // } // } // // public static void i(String mess) { // if (DEBUG) { // Log.i(getTag(), mess); // } // } // // public static void w(String mess) { // if (DEBUG) { // Log.w(getTag(), mess); // } // } // // public static void e(String mess) { // if (DEBUG) { // Log.e(getTag(), mess); // } // } // // private static String getTag() { // StackTraceElement[] trace = new Throwable().fillInStackTrace() // .getStackTrace(); // String callingClass = ""; // for (int i = 2; i < trace.length; i++) { // Class<?> clazz = trace[i].getClass(); // if (!clazz.equals(LogUtil.class)) { // callingClass = trace[i].getClassName(); // callingClass = callingClass.substring(callingClass // .lastIndexOf('.') + 1); // break; // } // } // return callingClass; // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/activity/WebActivity.java import android.webkit.WebSettings; import android.webkit.WebView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.util.Keys; import com.github.cchao.touchnews.util.LogUtil; import butterknife.Bind; package com.github.cchao.touchnews.ui.activity; /** * Created by cchao on 2016/8/19. * E-mail: cchao1024@163.com * Description: 网页显示页 */ public class WebActivity extends BaseActivity { @Bind(R.id.webview_article_detail) WebView mWebView; @Override protected int getLayoutID() { return R.layout.activity_web; } @Override protected void initialize() { super.initialize(); setWebView();
mWebView.loadUrl(getIntent().getStringExtra(Keys.URL));
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/activity/WebActivity.java
// Path: app/src/main/java/com/github/cchao/touchnews/util/Keys.java // public class Keys { // public static final String BAI_DU_KEY = "96a573502b09d771c6431c106d04613a"; // public static final String BAI_DU_API_KEY = "1bb91df70ccde8148a2c3da582ca9ff2"; // public static final String API_KEY = "apikey"; // public static final String KEY = "key"; // public static final String URL = "url"; // public static final String CITY = "city"; // public static final String INFO = "info"; // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/LogUtil.java // public class LogUtil { // public static final boolean DEBUG = true; // // public static void v(String tag, String mess) { // if (DEBUG) { // Log.v(tag, mess); // } // } // // public static void d(String tag, String mess) { // if (DEBUG) { // Log.d(tag, mess); // } // } // // public static void i(String tag, String mess) { // if (DEBUG) { // Log.i(tag, mess); // } // } // // public static void w(String tag, String mess) { // if (DEBUG) { // Log.w(tag, mess); // } // } // // public static void e(String tag, String mess) { // if (DEBUG) { // Log.e(tag, mess); // } // } // // public static void v(String mess) { // if (DEBUG) { // Log.v(getTag(), mess); // } // } // // public static void d(String mess) { // if (DEBUG) { // Log.d(getTag(), mess); // } // } // // public static void i(String mess) { // if (DEBUG) { // Log.i(getTag(), mess); // } // } // // public static void w(String mess) { // if (DEBUG) { // Log.w(getTag(), mess); // } // } // // public static void e(String mess) { // if (DEBUG) { // Log.e(getTag(), mess); // } // } // // private static String getTag() { // StackTraceElement[] trace = new Throwable().fillInStackTrace() // .getStackTrace(); // String callingClass = ""; // for (int i = 2; i < trace.length; i++) { // Class<?> clazz = trace[i].getClass(); // if (!clazz.equals(LogUtil.class)) { // callingClass = trace[i].getClassName(); // callingClass = callingClass.substring(callingClass // .lastIndexOf('.') + 1); // break; // } // } // return callingClass; // } // }
import android.webkit.WebSettings; import android.webkit.WebView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.util.Keys; import com.github.cchao.touchnews.util.LogUtil; import butterknife.Bind;
package com.github.cchao.touchnews.ui.activity; /** * Created by cchao on 2016/8/19. * E-mail: cchao1024@163.com * Description: 网页显示页 */ public class WebActivity extends BaseActivity { @Bind(R.id.webview_article_detail) WebView mWebView; @Override protected int getLayoutID() { return R.layout.activity_web; } @Override protected void initialize() { super.initialize(); setWebView(); mWebView.loadUrl(getIntent().getStringExtra(Keys.URL));
// Path: app/src/main/java/com/github/cchao/touchnews/util/Keys.java // public class Keys { // public static final String BAI_DU_KEY = "96a573502b09d771c6431c106d04613a"; // public static final String BAI_DU_API_KEY = "1bb91df70ccde8148a2c3da582ca9ff2"; // public static final String API_KEY = "apikey"; // public static final String KEY = "key"; // public static final String URL = "url"; // public static final String CITY = "city"; // public static final String INFO = "info"; // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/LogUtil.java // public class LogUtil { // public static final boolean DEBUG = true; // // public static void v(String tag, String mess) { // if (DEBUG) { // Log.v(tag, mess); // } // } // // public static void d(String tag, String mess) { // if (DEBUG) { // Log.d(tag, mess); // } // } // // public static void i(String tag, String mess) { // if (DEBUG) { // Log.i(tag, mess); // } // } // // public static void w(String tag, String mess) { // if (DEBUG) { // Log.w(tag, mess); // } // } // // public static void e(String tag, String mess) { // if (DEBUG) { // Log.e(tag, mess); // } // } // // public static void v(String mess) { // if (DEBUG) { // Log.v(getTag(), mess); // } // } // // public static void d(String mess) { // if (DEBUG) { // Log.d(getTag(), mess); // } // } // // public static void i(String mess) { // if (DEBUG) { // Log.i(getTag(), mess); // } // } // // public static void w(String mess) { // if (DEBUG) { // Log.w(getTag(), mess); // } // } // // public static void e(String mess) { // if (DEBUG) { // Log.e(getTag(), mess); // } // } // // private static String getTag() { // StackTraceElement[] trace = new Throwable().fillInStackTrace() // .getStackTrace(); // String callingClass = ""; // for (int i = 2; i < trace.length; i++) { // Class<?> clazz = trace[i].getClass(); // if (!clazz.equals(LogUtil.class)) { // callingClass = trace[i].getClassName(); // callingClass = callingClass.substring(callingClass // .lastIndexOf('.') + 1); // break; // } // } // return callingClass; // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/activity/WebActivity.java import android.webkit.WebSettings; import android.webkit.WebView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.util.Keys; import com.github.cchao.touchnews.util.LogUtil; import butterknife.Bind; package com.github.cchao.touchnews.ui.activity; /** * Created by cchao on 2016/8/19. * E-mail: cchao1024@163.com * Description: 网页显示页 */ public class WebActivity extends BaseActivity { @Bind(R.id.webview_article_detail) WebView mWebView; @Override protected int getLayoutID() { return R.layout.activity_web; } @Override protected void initialize() { super.initialize(); setWebView(); mWebView.loadUrl(getIntent().getStringExtra(Keys.URL));
LogUtil.i(getIntent().getStringExtra(Keys.URL));
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // }
import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List;
package com.github.cchao.touchnews.music; /** * Created by cchao on 2016/4/18. * E-mail: cchao1024@163.com * Description: 音乐播放器 */ public class MusicPlayer implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener { private final static String TAG = MusicPlayer.class.getSimpleName(); private final static long SLEEP_TIME = 1000; public boolean isPause; public MusicPlayerStateListener mPlayerStateListener; private MediaPlayer mMediaPlayer;
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // } // Path: app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; package com.github.cchao.touchnews.music; /** * Created by cchao on 2016/4/18. * E-mail: cchao1024@163.com * Description: 音乐播放器 */ public class MusicPlayer implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener { private final static String TAG = MusicPlayer.class.getSimpleName(); private final static long SLEEP_TIME = 1000; public boolean isPause; public MusicPlayerStateListener mPlayerStateListener; private MediaPlayer mMediaPlayer;
private List<MusicEntity> mMusicList;
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // }
import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List;
} public void setMusicList(List<MusicEntity> musicList) { mMusicList = musicList; mMediaPlayer.reset(); } public void addMusic(MusicEntity music) { if (music != null) { mMusicList.add(music); } } public int getMusicListCount() { return null == mMusicList || mMusicList.isEmpty() ? 0 : mMusicList.size(); } public MusicEntity getCurMusic() { return mCurMusic; } /** * 用户点击播放键 */ public void play() { if (isPause) { //暂停后再播放 mMediaPlayer.start(); isPause = false;
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // } // Path: app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; } public void setMusicList(List<MusicEntity> musicList) { mMusicList = musicList; mMediaPlayer.reset(); } public void addMusic(MusicEntity music) { if (music != null) { mMusicList.add(music); } } public int getMusicListCount() { return null == mMusicList || mMusicList.isEmpty() ? 0 : mMusicList.size(); } public MusicEntity getCurMusic() { return mCurMusic; } /** * 用户点击播放键 */ public void play() { if (isPause) { //暂停后再播放 mMediaPlayer.start(); isPause = false;
EventBus.getDefault().post(new MusicEvent(MusicEvent.MUSIC_TYPE.RESUME_PALY));
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // }
import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List;
} public void pauseM() { mMediaPlayer.pause(); isPause = true; EventBus.getDefault().post(new MusicEvent(MusicEvent.MUSIC_TYPE.PAUSE)); if (mPlayerStateListener != null) { mPlayerStateListener.onPause(); } } public void stop() { mMediaPlayer.stop(); EventBus.getDefault().post(new MusicEvent(MusicEvent.MUSIC_TYPE.STOP)); if (mPlayerStateListener != null) { mPlayerStateListener.onStop(); } } /** * 播放下一首 */ public void playNext() { //列表如果还有歌曲、播放下一首 if (mMusicList.size() > 0) { // mCurMusic = mMusicList.remove ( 0 ); mMediaPlayer.stop(); play(); } else {
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/MusicEntity.java // public class MusicEntity { // private Data mMusicInfo; // private MusicPathRoot.Data mMusicPath; // private MusicSingerRoot.Data mMusicSinger; // // public MusicEntity(Data data) { // mMusicInfo = data; // } // // public MusicPathRoot.Data getMusicPath() { // return mMusicPath; // } // // public void setMusicPath(MusicPathRoot.Data musicPath) { // mMusicPath = musicPath; // } // // public MusicSingerRoot.Data getMusicSinger() { // return mMusicSinger; // } // // public void setMusicSinger(MusicSingerRoot.Data musicSinger) { // mMusicSinger = musicSinger; // } // // public Data getMusicInfo() { // // return mMusicInfo; // } // // public void setMusicInfo(Data musicInfo) { // mMusicInfo = musicInfo; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/javaBean/event/MusicEvent.java // public class MusicEvent { // public enum MUSIC_TYPE { // PREPARE, PLAY, PAUSE, RESUME_PALY, STOP // } // // private MUSIC_TYPE type; // // public MusicEvent(MUSIC_TYPE type) { // this.type = type; // } // // public MUSIC_TYPE getType() { // return type; // } // // public void setType(MUSIC_TYPE type) { // this.type = type; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/ToastUtil.java // public class ToastUtil { // private static Toast toast; // private static View view; // // private ToastUtil() { // } // // @SuppressLint("ShowToast") // private static void getToast(Context context) { // if (toast == null) { // toast = new Toast(context); // } // if (view == null) { // view = Toast.makeText(context, "", Toast.LENGTH_SHORT).getView(); // } // toast.setView(view); // } // // public static void showShortToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_SHORT); // } // } // // public static void showShortToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_SHORT); // } // // public static void showShortToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } // // public static void showShortToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_SHORT); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_SHORT); // } // } // // public static void showLongToast(CharSequence msg) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } // // public static void showLongToast(Context context, CharSequence msg) { // if (context == null) { // showToast(BaseApplication.getContext(), msg, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), msg, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(Context context, int resId) { // if (context == null) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // } else { // showToast(context.getApplicationContext(), resId, Toast.LENGTH_LONG); // } // } // // public static void showLongToast(@StringRes int resId) { // showToast(BaseApplication.getContext(), resId, Toast.LENGTH_LONG); // // } // // private static void showToast(Context context, CharSequence msg, int duration) { // try { // getToast(context); // toast.setText(msg); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // private static void showToast(Context context, int resId, int duration) { // try { // if (resId == 0) { // return; // } // getToast(context); // toast.setText(resId); // toast.setDuration(duration); // toast.show(); // } catch (Exception e) { // LogUtil.d(e.getMessage()); // } // } // // } // Path: app/src/main/java/com/github/cchao/touchnews/music/MusicPlayer.java import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import com.github.cchao.touchnews.javaBean.MusicEntity; import com.github.cchao.touchnews.javaBean.event.MusicEvent; import com.github.cchao.touchnews.util.ToastUtil; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; } public void pauseM() { mMediaPlayer.pause(); isPause = true; EventBus.getDefault().post(new MusicEvent(MusicEvent.MUSIC_TYPE.PAUSE)); if (mPlayerStateListener != null) { mPlayerStateListener.onPause(); } } public void stop() { mMediaPlayer.stop(); EventBus.getDefault().post(new MusicEvent(MusicEvent.MUSIC_TYPE.STOP)); if (mPlayerStateListener != null) { mPlayerStateListener.onStop(); } } /** * 播放下一首 */ public void playNext() { //列表如果还有歌曲、播放下一首 if (mMusicList.size() > 0) { // mCurMusic = mMusicList.remove ( 0 ); mMediaPlayer.stop(); play(); } else {
ToastUtil.showShortToast(null, "没有下一首了");
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeContainerFragment.java
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/JokeFragmentsContainerPresenter.java // public class JokeFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // FragmentContainerContract.View mView; // List<BaseFragment> mFragments; // String[] mTitles; // // public JokeFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // @Override // public List<BaseFragment> getFragments() { // mFragments = new ArrayList<>(); // mFragments.add(new JokeTextListFragments()); // mFragments.add(new JokeImageListFragments()); // return mFragments; // } // // @Override // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.joke_titles); // return mTitles; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeFragmentsPagerAdapter.java // public class JokeFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<Fragment> mListFragments = null; // private String[] mTitles = null; // // public JokeFragmentsPagerAdapter(FragmentManager fm, String[] titles, List fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // }
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.JokeFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.JokeFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind;
package com.github.cchao.touchnews.ui.fragment; /** * Created by cchao on 2016/4/25. * E-mail: cchao1024@163.com * Description: 开心一下容器Fragment */ public class JokeContainerFragment extends BaseFragment implements FragmentContainerContract.View { @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.tab_joke_image) TabLayout mTabLayout; @Bind(R.id.viewpager_joke_image) ViewPager mViewPager; FragmentPagerAdapter mFragmentsPagerAdapter; FragmentContainerContract.Presenter mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onFirstUserVisible() { super.onFirstUserVisible();
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/JokeFragmentsContainerPresenter.java // public class JokeFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // FragmentContainerContract.View mView; // List<BaseFragment> mFragments; // String[] mTitles; // // public JokeFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // @Override // public List<BaseFragment> getFragments() { // mFragments = new ArrayList<>(); // mFragments.add(new JokeTextListFragments()); // mFragments.add(new JokeImageListFragments()); // return mFragments; // } // // @Override // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.joke_titles); // return mTitles; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeFragmentsPagerAdapter.java // public class JokeFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<Fragment> mListFragments = null; // private String[] mTitles = null; // // public JokeFragmentsPagerAdapter(FragmentManager fm, String[] titles, List fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeContainerFragment.java import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.JokeFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.JokeFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind; package com.github.cchao.touchnews.ui.fragment; /** * Created by cchao on 2016/4/25. * E-mail: cchao1024@163.com * Description: 开心一下容器Fragment */ public class JokeContainerFragment extends BaseFragment implements FragmentContainerContract.View { @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.tab_joke_image) TabLayout mTabLayout; @Bind(R.id.viewpager_joke_image) ViewPager mViewPager; FragmentPagerAdapter mFragmentsPagerAdapter; FragmentContainerContract.Presenter mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onFirstUserVisible() { super.onFirstUserVisible();
mPresenter = new JokeFragmentsContainerPresenter(this);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeContainerFragment.java
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/JokeFragmentsContainerPresenter.java // public class JokeFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // FragmentContainerContract.View mView; // List<BaseFragment> mFragments; // String[] mTitles; // // public JokeFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // @Override // public List<BaseFragment> getFragments() { // mFragments = new ArrayList<>(); // mFragments.add(new JokeTextListFragments()); // mFragments.add(new JokeImageListFragments()); // return mFragments; // } // // @Override // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.joke_titles); // return mTitles; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeFragmentsPagerAdapter.java // public class JokeFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<Fragment> mListFragments = null; // private String[] mTitles = null; // // public JokeFragmentsPagerAdapter(FragmentManager fm, String[] titles, List fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // }
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.JokeFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.JokeFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind;
public void onFirstUserVisible() { super.onFirstUserVisible(); mPresenter = new JokeFragmentsContainerPresenter(this); mPresenter.getFragments(); mToolbar.setTitle(R.string.joke); } @Override protected int getLayoutId() { return R.layout.fragment_joke_container; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; } return false; } @Override public void setFragment(List<BaseFragment> fragments, String[] titles) {
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/JokeFragmentsContainerPresenter.java // public class JokeFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // FragmentContainerContract.View mView; // List<BaseFragment> mFragments; // String[] mTitles; // // public JokeFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // @Override // public List<BaseFragment> getFragments() { // mFragments = new ArrayList<>(); // mFragments.add(new JokeTextListFragments()); // mFragments.add(new JokeImageListFragments()); // return mFragments; // } // // @Override // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.joke_titles); // return mTitles; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeFragmentsPagerAdapter.java // public class JokeFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<Fragment> mListFragments = null; // private String[] mTitles = null; // // public JokeFragmentsPagerAdapter(FragmentManager fm, String[] titles, List fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeContainerFragment.java import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.JokeFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.JokeFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind; public void onFirstUserVisible() { super.onFirstUserVisible(); mPresenter = new JokeFragmentsContainerPresenter(this); mPresenter.getFragments(); mToolbar.setTitle(R.string.joke); } @Override protected int getLayoutId() { return R.layout.fragment_joke_container; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; } return false; } @Override public void setFragment(List<BaseFragment> fragments, String[] titles) {
mFragmentsPagerAdapter = new JokeFragmentsPagerAdapter(getActivity().getSupportFragmentManager(), titles, fragments);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java
// Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/UrlUtil.java // public class UrlUtil { // //baiDu_apiKey // public static final String API_KEY = "96a573502b09d771c6431c106d04613a"; // //BaiDu_url // public static final String API_BAI_DU = "http://apis.baidu.com/"; // //turing_apiKey // public static final String TURING_KEY = "16d2878f1e41520c14dde5ed52920423"; // //新闻api // public static final String URL_NEWS = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news"; // //图片笑话 // public static final String URL_JOKE_IMAGE = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_pic"; // //文字笑话 // public static final String URL_JOKE_Text = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text"; // //天气api // public static final String URL_WEATHER = "http://apis.baidu.com/heweather/weather/free"; // //音乐Hash api // public static final String URL_MUSIC_HASH = "http://apis.baidu.com/geekery/music/query"; // //音乐地址 api // public static final String URL_MUSIC_INFO = "http://apis.baidu.com/geekery/music/playinfo"; // //歌手信息 api // public static final String URL_MUSIC_SINGER = "http://apis.baidu.com/geekery/music/singer"; // //通过IP获取定位城市 // public static final String URL_CITY = "http://pv.sohu.com/cityjson"; // //图灵api // public static final String URL_CHAT = "http://www.tuling123.com/openapi/api"; // }
import android.support.annotation.NonNull; import com.github.cchao.touchnews.util.BaiDuApiService; import com.github.cchao.touchnews.util.UrlUtil; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.github.cchao.touchnews.di.module; /** * Created by cchao on 2016/8/23. * E-mail: cchao1024@163.com * Description: api module */ @Module public class ApiModule { /** * @param baseUrl baseUrl * @return Retrofit 对象 */ private Retrofit getApiService(@NonNull String baseUrl) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(baseUrl) .build(); } /** * @return 百度的api接口 */ @Singleton @Provides
// Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/UrlUtil.java // public class UrlUtil { // //baiDu_apiKey // public static final String API_KEY = "96a573502b09d771c6431c106d04613a"; // //BaiDu_url // public static final String API_BAI_DU = "http://apis.baidu.com/"; // //turing_apiKey // public static final String TURING_KEY = "16d2878f1e41520c14dde5ed52920423"; // //新闻api // public static final String URL_NEWS = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news"; // //图片笑话 // public static final String URL_JOKE_IMAGE = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_pic"; // //文字笑话 // public static final String URL_JOKE_Text = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text"; // //天气api // public static final String URL_WEATHER = "http://apis.baidu.com/heweather/weather/free"; // //音乐Hash api // public static final String URL_MUSIC_HASH = "http://apis.baidu.com/geekery/music/query"; // //音乐地址 api // public static final String URL_MUSIC_INFO = "http://apis.baidu.com/geekery/music/playinfo"; // //歌手信息 api // public static final String URL_MUSIC_SINGER = "http://apis.baidu.com/geekery/music/singer"; // //通过IP获取定位城市 // public static final String URL_CITY = "http://pv.sohu.com/cityjson"; // //图灵api // public static final String URL_CHAT = "http://www.tuling123.com/openapi/api"; // } // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java import android.support.annotation.NonNull; import com.github.cchao.touchnews.util.BaiDuApiService; import com.github.cchao.touchnews.util.UrlUtil; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.github.cchao.touchnews.di.module; /** * Created by cchao on 2016/8/23. * E-mail: cchao1024@163.com * Description: api module */ @Module public class ApiModule { /** * @param baseUrl baseUrl * @return Retrofit 对象 */ private Retrofit getApiService(@NonNull String baseUrl) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(baseUrl) .build(); } /** * @return 百度的api接口 */ @Singleton @Provides
protected BaiDuApiService provideBaiDuApiService() {
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java
// Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/UrlUtil.java // public class UrlUtil { // //baiDu_apiKey // public static final String API_KEY = "96a573502b09d771c6431c106d04613a"; // //BaiDu_url // public static final String API_BAI_DU = "http://apis.baidu.com/"; // //turing_apiKey // public static final String TURING_KEY = "16d2878f1e41520c14dde5ed52920423"; // //新闻api // public static final String URL_NEWS = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news"; // //图片笑话 // public static final String URL_JOKE_IMAGE = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_pic"; // //文字笑话 // public static final String URL_JOKE_Text = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text"; // //天气api // public static final String URL_WEATHER = "http://apis.baidu.com/heweather/weather/free"; // //音乐Hash api // public static final String URL_MUSIC_HASH = "http://apis.baidu.com/geekery/music/query"; // //音乐地址 api // public static final String URL_MUSIC_INFO = "http://apis.baidu.com/geekery/music/playinfo"; // //歌手信息 api // public static final String URL_MUSIC_SINGER = "http://apis.baidu.com/geekery/music/singer"; // //通过IP获取定位城市 // public static final String URL_CITY = "http://pv.sohu.com/cityjson"; // //图灵api // public static final String URL_CHAT = "http://www.tuling123.com/openapi/api"; // }
import android.support.annotation.NonNull; import com.github.cchao.touchnews.util.BaiDuApiService; import com.github.cchao.touchnews.util.UrlUtil; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.github.cchao.touchnews.di.module; /** * Created by cchao on 2016/8/23. * E-mail: cchao1024@163.com * Description: api module */ @Module public class ApiModule { /** * @param baseUrl baseUrl * @return Retrofit 对象 */ private Retrofit getApiService(@NonNull String baseUrl) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(baseUrl) .build(); } /** * @return 百度的api接口 */ @Singleton @Provides protected BaiDuApiService provideBaiDuApiService() {
// Path: app/src/main/java/com/github/cchao/touchnews/util/BaiDuApiService.java // public interface BaiDuApiService { // //新闻api // @GET("showapi_open_bus/channel_news/search_news") // Observable<NewsItemRoot> getNews(@Header("apikey") String apikey, @Query("channelId") String channelID, @Query("page") String // page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_text") // Observable<JokeTextRoot> getJokeText(@Header("apikey") String apikey, @Query("page") String page); // // //笑话集 // @GET("showapi_open_bus/showapi_joke/joke_pic") // Observable<JokeImageRoot> getJokeImage(@Header("apikey") String apikey, @Query("page") String page); // // //响应根据关键字获取的歌曲列表 // @GET("geekery/music/query") // Observable<MusicInfoRoot> getMusicList(@Header("apikey") String apikey, @Query("s") String s); // // //获取Music播放地址 // @GET("geekery/music/playinfo") // Observable<MusicPathRoot> getMusicPath(@Header("apikey") String apikey, @Query("hash") String hash); // // //歌手信息 // @GET("geekery/music/singer") // Observable<MusicSingerRoot> getSinger(@Header("apikey") String apikey, @Query("name") String name); // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/util/UrlUtil.java // public class UrlUtil { // //baiDu_apiKey // public static final String API_KEY = "96a573502b09d771c6431c106d04613a"; // //BaiDu_url // public static final String API_BAI_DU = "http://apis.baidu.com/"; // //turing_apiKey // public static final String TURING_KEY = "16d2878f1e41520c14dde5ed52920423"; // //新闻api // public static final String URL_NEWS = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news"; // //图片笑话 // public static final String URL_JOKE_IMAGE = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_pic"; // //文字笑话 // public static final String URL_JOKE_Text = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text"; // //天气api // public static final String URL_WEATHER = "http://apis.baidu.com/heweather/weather/free"; // //音乐Hash api // public static final String URL_MUSIC_HASH = "http://apis.baidu.com/geekery/music/query"; // //音乐地址 api // public static final String URL_MUSIC_INFO = "http://apis.baidu.com/geekery/music/playinfo"; // //歌手信息 api // public static final String URL_MUSIC_SINGER = "http://apis.baidu.com/geekery/music/singer"; // //通过IP获取定位城市 // public static final String URL_CITY = "http://pv.sohu.com/cityjson"; // //图灵api // public static final String URL_CHAT = "http://www.tuling123.com/openapi/api"; // } // Path: app/src/main/java/com/github/cchao/touchnews/di/module/ApiModule.java import android.support.annotation.NonNull; import com.github.cchao.touchnews.util.BaiDuApiService; import com.github.cchao.touchnews.util.UrlUtil; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.github.cchao.touchnews.di.module; /** * Created by cchao on 2016/8/23. * E-mail: cchao1024@163.com * Description: api module */ @Module public class ApiModule { /** * @param baseUrl baseUrl * @return Retrofit 对象 */ private Retrofit getApiService(@NonNull String baseUrl) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .baseUrl(baseUrl) .build(); } /** * @return 百度的api接口 */ @Singleton @Provides protected BaiDuApiService provideBaiDuApiService() {
return getApiService(UrlUtil.API_BAI_DU).create(BaiDuApiService.class);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/fragment/NewsContainerFragment.java
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/NewsFragmentsContainerPresenter.java // public class NewsFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // List<BaseFragment> mFragments; // String[] mTitles; // FragmentContainerContract.View mView; // // public NewsFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // /** // * @return 新闻频道List // */ // public List<BaseFragment> getFragments() { // if (mFragments == null) { // mFragments = new ArrayList<>(); // //Arguments 加入新闻频道ID // String[] newsChannelId = BaseApplication.getContext().getResources().getStringArray(R.array.news_channelId); // for (int i = 0; i < newsChannelId.length; i++) { // NewsListFragments newsListFragments = new NewsListFragments(); // // Bundle bundle= new Bundle ( ); // // bundle.putString ( "channelId", newsChannelId[ i ] ); // // newsListFragments.setArguments ( bundle ); // newsListFragments.setChannelId(newsChannelId[i]); // mFragments.add(newsListFragments); // } // } // return mFragments; // } // // /** // * @return 新闻页的标题 // */ // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.news_titles); // return mTitles; // } // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/NewsFragmentsPagerAdapter.java // public class NewsFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<BaseFragment> mListFragments = null; // private String[] mTitles = null; // // public NewsFragmentsPagerAdapter(FragmentManager fm, String[] titles, List<BaseFragment> fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // }
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.NewsFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.NewsFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind;
package com.github.cchao.touchnews.ui.fragment; /** * Created by cchao on 2016/3/30. * E-mail: cchao1024@163.com * Description: 新闻资讯容器Fragment */ public class NewsContainerFragment extends BaseFragment implements FragmentContainerContract.View { @Bind(R.id.tab_news) TabLayout mTabLayout; @Bind(R.id.viewpager_news) ViewPager mViewPager; FragmentPagerAdapter mFragmentsPagerAdapter; FragmentContainerContract.Presenter mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } protected int getLayoutId() { return R.layout.fragment_news_container; } @Override protected void initialize() { super.initialize();
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/NewsFragmentsContainerPresenter.java // public class NewsFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // List<BaseFragment> mFragments; // String[] mTitles; // FragmentContainerContract.View mView; // // public NewsFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // /** // * @return 新闻频道List // */ // public List<BaseFragment> getFragments() { // if (mFragments == null) { // mFragments = new ArrayList<>(); // //Arguments 加入新闻频道ID // String[] newsChannelId = BaseApplication.getContext().getResources().getStringArray(R.array.news_channelId); // for (int i = 0; i < newsChannelId.length; i++) { // NewsListFragments newsListFragments = new NewsListFragments(); // // Bundle bundle= new Bundle ( ); // // bundle.putString ( "channelId", newsChannelId[ i ] ); // // newsListFragments.setArguments ( bundle ); // newsListFragments.setChannelId(newsChannelId[i]); // mFragments.add(newsListFragments); // } // } // return mFragments; // } // // /** // * @return 新闻页的标题 // */ // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.news_titles); // return mTitles; // } // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/NewsFragmentsPagerAdapter.java // public class NewsFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<BaseFragment> mListFragments = null; // private String[] mTitles = null; // // public NewsFragmentsPagerAdapter(FragmentManager fm, String[] titles, List<BaseFragment> fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/NewsContainerFragment.java import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.NewsFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.NewsFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind; package com.github.cchao.touchnews.ui.fragment; /** * Created by cchao on 2016/3/30. * E-mail: cchao1024@163.com * Description: 新闻资讯容器Fragment */ public class NewsContainerFragment extends BaseFragment implements FragmentContainerContract.View { @Bind(R.id.tab_news) TabLayout mTabLayout; @Bind(R.id.viewpager_news) ViewPager mViewPager; FragmentPagerAdapter mFragmentsPagerAdapter; FragmentContainerContract.Presenter mPresenter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } protected int getLayoutId() { return R.layout.fragment_news_container; } @Override protected void initialize() { super.initialize();
mPresenter = new NewsFragmentsContainerPresenter(this);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/fragment/NewsContainerFragment.java
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/NewsFragmentsContainerPresenter.java // public class NewsFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // List<BaseFragment> mFragments; // String[] mTitles; // FragmentContainerContract.View mView; // // public NewsFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // /** // * @return 新闻频道List // */ // public List<BaseFragment> getFragments() { // if (mFragments == null) { // mFragments = new ArrayList<>(); // //Arguments 加入新闻频道ID // String[] newsChannelId = BaseApplication.getContext().getResources().getStringArray(R.array.news_channelId); // for (int i = 0; i < newsChannelId.length; i++) { // NewsListFragments newsListFragments = new NewsListFragments(); // // Bundle bundle= new Bundle ( ); // // bundle.putString ( "channelId", newsChannelId[ i ] ); // // newsListFragments.setArguments ( bundle ); // newsListFragments.setChannelId(newsChannelId[i]); // mFragments.add(newsListFragments); // } // } // return mFragments; // } // // /** // * @return 新闻页的标题 // */ // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.news_titles); // return mTitles; // } // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/NewsFragmentsPagerAdapter.java // public class NewsFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<BaseFragment> mListFragments = null; // private String[] mTitles = null; // // public NewsFragmentsPagerAdapter(FragmentManager fm, String[] titles, List<BaseFragment> fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // }
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.NewsFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.NewsFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind;
@Override public void onFirstUserVisible() { super.onFirstUserVisible(); mToolbar.setTitle(R.string.news); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; } return false; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu, inflater); } /** * 设置新闻频道块 * * @param fragments 块 * @param titles 标题 */ @Override public void setFragment(List<BaseFragment> fragments, String[] titles) {
// Path: app/src/main/java/com/github/cchao/touchnews/contract/FragmentContainerContract.java // public interface FragmentContainerContract { // // interface View { // void setFragment(List<BaseFragment> fragments, String[] titles); // } // // interface Presenter { // List<BaseFragment> getFragments(); // // String[] getTitles(); // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/presenter/NewsFragmentsContainerPresenter.java // public class NewsFragmentsContainerPresenter implements FragmentContainerContract.Presenter { // List<BaseFragment> mFragments; // String[] mTitles; // FragmentContainerContract.View mView; // // public NewsFragmentsContainerPresenter(FragmentContainerContract.View view) { // mView = view; // mView.setFragment(getFragments(), getTitles()); // } // // /** // * @return 新闻频道List // */ // public List<BaseFragment> getFragments() { // if (mFragments == null) { // mFragments = new ArrayList<>(); // //Arguments 加入新闻频道ID // String[] newsChannelId = BaseApplication.getContext().getResources().getStringArray(R.array.news_channelId); // for (int i = 0; i < newsChannelId.length; i++) { // NewsListFragments newsListFragments = new NewsListFragments(); // // Bundle bundle= new Bundle ( ); // // bundle.putString ( "channelId", newsChannelId[ i ] ); // // newsListFragments.setArguments ( bundle ); // newsListFragments.setChannelId(newsChannelId[i]); // mFragments.add(newsListFragments); // } // } // return mFragments; // } // // /** // * @return 新闻页的标题 // */ // public String[] getTitles() { // mTitles = BaseApplication.getContext().getResources().getStringArray(R.array.news_titles); // return mTitles; // } // // // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/NewsFragmentsPagerAdapter.java // public class NewsFragmentsPagerAdapter extends FragmentPagerAdapter { // private List<BaseFragment> mListFragments = null; // private String[] mTitles = null; // // public NewsFragmentsPagerAdapter(FragmentManager fm, String[] titles, List<BaseFragment> fragments) { // super(fm); // mListFragments = fragments; // mTitles = titles; // // } // // @Override // public int getCount() { // if (mListFragments != null) { // return mListFragments.size(); // } else { // return 0; // } // } // // @Override // public Fragment getItem(int position) { // if (mListFragments != null && position >= 0 && position < mListFragments.size()) { // return mListFragments.get(position); // } else { // return null; // } // } // // @Override // public CharSequence getPageTitle(int position) { // return mTitles[position]; // } // } // // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/base/BaseFragment.java // public abstract class BaseFragment extends BaseLazyFragment { // protected Toolbar mToolbar; // protected View mRootView; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mRootView = inflater.inflate(getLayoutId(), null); // ButterKnife.bind(this, mRootView); // mToolbar = ButterKnife.findById(mRootView, R.id.toolbar); // return mRootView; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // initialize(); // } // // protected void initialize() { // } // // @Override // public void onFirstUserVisible() { // super.onFirstUserVisible(); // setSupportActionBar(); // } // // //布局ID // protected abstract // @LayoutRes // int getLayoutId(); // // @Override // public void onUserVisible() { // super.onUserVisible(); // setSupportActionBar(); // } // // /** // * 设置toolbar // */ // private void setSupportActionBar() { // ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar); // ((HomeActivity) getActivity()).addDrawerListener(mToolbar); // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/fragment/NewsContainerFragment.java import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.FragmentContainerContract; import com.github.cchao.touchnews.presenter.NewsFragmentsContainerPresenter; import com.github.cchao.touchnews.ui.adapter.NewsFragmentsPagerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import java.util.List; import butterknife.Bind; @Override public void onFirstUserVisible() { super.onFirstUserVisible(); mToolbar.setTitle(R.string.news); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; } return false; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu, inflater); } /** * 设置新闻频道块 * * @param fragments 块 * @param titles 标题 */ @Override public void setFragment(List<BaseFragment> fragments, String[] titles) {
mFragmentsPagerAdapter = new NewsFragmentsPagerAdapter(getActivity().getSupportFragmentManager(), titles, fragments);
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeTextListRecyclerAdapter.java
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/joke/JokeTextRoot.java // public class JokeTextRoot { // private int showapi_res_code; // // private String showapi_res_error; // // private Showapi_res_body showapi_res_body; // // public void setShowapi_res_code(int showapi_res_code) { // this.showapi_res_code = showapi_res_code; // } // // public int getShowapi_res_code() { // return this.showapi_res_code; // } // // public void setShowapi_res_error(String showapi_res_error) { // this.showapi_res_error = showapi_res_error; // } // // public String getShowapi_res_error() { // return this.showapi_res_error; // } // // public void setShowapi_res_body(Showapi_res_body showapi_res_body) { // this.showapi_res_body = showapi_res_body; // } // // public Showapi_res_body getShowapi_res_body() { // return this.showapi_res_body; // } // // public static class Showapi_res_body { // private int allNum; // // private int allPages; // // private List<Contentlist> contentlist; // // private int currentPage; // // private int maxResult; // // private int ret_code; // // public void setAllNum(int allNum) { // this.allNum = allNum; // } // // public int getAllNum() { // return this.allNum; // } // // public void setAllPages(int allPages) { // this.allPages = allPages; // } // // public int getAllPages() { // return this.allPages; // } // // public void setContentlist(List<Contentlist> contentlist) { // this.contentlist = contentlist; // } // // public List<Contentlist> getContentlist() { // return this.contentlist; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getCurrentPage() { // return this.currentPage; // } // // public void setMaxResult(int maxResult) { // this.maxResult = maxResult; // } // // public int getMaxResult() { // return this.maxResult; // } // // public void setRet_code(int ret_code) { // this.ret_code = ret_code; // } // // public int getRet_code() { // return this.ret_code; // } // // } // // /** // * Created by cchao on 2016/4/25. // * E-mail: cchao1024@163.com // * Description: // */ // public static class Contentlist { // private String ct; // // private String text; // // private String title; // // private int type; // // public void setCt(String ct) { // this.ct = ct; // } // // public String getCt() { // return this.ct; // } // // public void setText(String img) { // this.text = img; // } // // public String getText() { // return this.text; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return this.title; // } // // public void setType(int type) { // this.type = type; // } // // public int getType() { // return this.type; // } // // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.javaBean.joke.JokeTextRoot; import java.util.List;
package com.github.cchao.touchnews.ui.adapter; /** * Created by cchao on 2016/4/5. * E-mail: cchao1024@163.com * Description: */ public class JokeTextListRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 0; private static final int TYPE_FOOTER = 1; public Context mContext;
// Path: app/src/main/java/com/github/cchao/touchnews/javaBean/joke/JokeTextRoot.java // public class JokeTextRoot { // private int showapi_res_code; // // private String showapi_res_error; // // private Showapi_res_body showapi_res_body; // // public void setShowapi_res_code(int showapi_res_code) { // this.showapi_res_code = showapi_res_code; // } // // public int getShowapi_res_code() { // return this.showapi_res_code; // } // // public void setShowapi_res_error(String showapi_res_error) { // this.showapi_res_error = showapi_res_error; // } // // public String getShowapi_res_error() { // return this.showapi_res_error; // } // // public void setShowapi_res_body(Showapi_res_body showapi_res_body) { // this.showapi_res_body = showapi_res_body; // } // // public Showapi_res_body getShowapi_res_body() { // return this.showapi_res_body; // } // // public static class Showapi_res_body { // private int allNum; // // private int allPages; // // private List<Contentlist> contentlist; // // private int currentPage; // // private int maxResult; // // private int ret_code; // // public void setAllNum(int allNum) { // this.allNum = allNum; // } // // public int getAllNum() { // return this.allNum; // } // // public void setAllPages(int allPages) { // this.allPages = allPages; // } // // public int getAllPages() { // return this.allPages; // } // // public void setContentlist(List<Contentlist> contentlist) { // this.contentlist = contentlist; // } // // public List<Contentlist> getContentlist() { // return this.contentlist; // } // // public void setCurrentPage(int currentPage) { // this.currentPage = currentPage; // } // // public int getCurrentPage() { // return this.currentPage; // } // // public void setMaxResult(int maxResult) { // this.maxResult = maxResult; // } // // public int getMaxResult() { // return this.maxResult; // } // // public void setRet_code(int ret_code) { // this.ret_code = ret_code; // } // // public int getRet_code() { // return this.ret_code; // } // // } // // /** // * Created by cchao on 2016/4/25. // * E-mail: cchao1024@163.com // * Description: // */ // public static class Contentlist { // private String ct; // // private String text; // // private String title; // // private int type; // // public void setCt(String ct) { // this.ct = ct; // } // // public String getCt() { // return this.ct; // } // // public void setText(String img) { // this.text = img; // } // // public String getText() { // return this.text; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return this.title; // } // // public void setType(int type) { // this.type = type; // } // // public int getType() { // return this.type; // } // // } // } // Path: app/src/main/java/com/github/cchao/touchnews/ui/adapter/JokeTextListRecyclerAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.javaBean.joke.JokeTextRoot; import java.util.List; package com.github.cchao.touchnews.ui.adapter; /** * Created by cchao on 2016/4/5. * E-mail: cchao1024@163.com * Description: */ public class JokeTextListRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 0; private static final int TYPE_FOOTER = 1; public Context mContext;
public List<JokeTextRoot.Contentlist> mData;
cloudspannerecosystem/pgadapter
src/test/java/com/google/cloud/spanner/pgadapter/MetadataTest.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DynamicCommandMetadata.java // public class DynamicCommandMetadata { // // private static final String COMMANDS_KEY = "commands"; // private static final String INPUT_KEY = "input_pattern"; // private static final String OUTPUT_KEY = "output_pattern"; // private static final String MATCHER_KEY = "matcher_array"; // // private String inputPattern; // private String outputPattern; // private List<String> matcherOrder; // // private DynamicCommandMetadata(JSONObject commandJSON) { // this.inputPattern = getJSONString(commandJSON, INPUT_KEY); // this.outputPattern = getJSONString(commandJSON, OUTPUT_KEY); // this.matcherOrder = new ArrayList<>(); // for (Object arrayObject : getJSONArray(commandJSON, MATCHER_KEY)) { // String argumentNumber = (String) arrayObject; // this.matcherOrder.add(argumentNumber); // } // } // // /** // * Takes a JSON object and returns a list of metadata objects holding the desired information. // * // * @param jsonObject Input JSON object in the format {"commands": [{"input_pattern": "", // * "output_pattern": "", "matcher_array": [number1, ...]}, ...]} // * @return A list of constructed metadata objects in the format understood by DynamicCommands // */ // public static List<DynamicCommandMetadata> fromJSON(JSONObject jsonObject) { // List<DynamicCommandMetadata> resultList = new ArrayList<>(); // for (Object currentJSONObject : getJSONArray(jsonObject, COMMANDS_KEY)) { // resultList.add(new DynamicCommandMetadata((JSONObject) currentJSONObject)); // } // return resultList; // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in String type. // */ // private static String getJSONString(JSONObject jsonObject, String key) { // return getJSONObject(jsonObject, key).toString(); // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONArray type. // */ // private static JSONArray getJSONArray(JSONObject jsonObject, String key) { // return (JSONArray) getJSONObject(jsonObject, key); // } // // /** // * Simple getter which transforms the result into the desired type. If the key does not exist, // * throw an exception. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONObject type. // * @throws IllegalArgumentException If the key doesn't exist. // */ // private static Object getJSONObject(JSONObject jsonObject, String key) { // Object result = jsonObject.get(key); // if (result == null) { // throw new IllegalArgumentException( // String.format("A '%s' key must be specified in the JSON definition.", key) // ); // } // return result; // } // // public String getInputPattern() { // return this.inputPattern; // } // // public String getOutputPattern() { // return this.outputPattern; // } // // public List<String> getMatcherOrder() { // return this.matcherOrder; // } // }
import com.google.cloud.spanner.pgadapter.metadata.DynamicCommandMetadata; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.junit.Assert; import org.junit.Test;
// Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class MetadataTest { @Test public void testDynamicCommandMetadataSingleCommand() throws Exception { String inputJSON = "" + "{" + " \"commands\": " + " [ " + " {" + " \"input_pattern\": \"this is the input SQL query\", " + " \"output_pattern\": \"this is the output SQL query\", " + " \"matcher_array\": []" + " }" + " ]" + "}"; JSONParser parser = new JSONParser();
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DynamicCommandMetadata.java // public class DynamicCommandMetadata { // // private static final String COMMANDS_KEY = "commands"; // private static final String INPUT_KEY = "input_pattern"; // private static final String OUTPUT_KEY = "output_pattern"; // private static final String MATCHER_KEY = "matcher_array"; // // private String inputPattern; // private String outputPattern; // private List<String> matcherOrder; // // private DynamicCommandMetadata(JSONObject commandJSON) { // this.inputPattern = getJSONString(commandJSON, INPUT_KEY); // this.outputPattern = getJSONString(commandJSON, OUTPUT_KEY); // this.matcherOrder = new ArrayList<>(); // for (Object arrayObject : getJSONArray(commandJSON, MATCHER_KEY)) { // String argumentNumber = (String) arrayObject; // this.matcherOrder.add(argumentNumber); // } // } // // /** // * Takes a JSON object and returns a list of metadata objects holding the desired information. // * // * @param jsonObject Input JSON object in the format {"commands": [{"input_pattern": "", // * "output_pattern": "", "matcher_array": [number1, ...]}, ...]} // * @return A list of constructed metadata objects in the format understood by DynamicCommands // */ // public static List<DynamicCommandMetadata> fromJSON(JSONObject jsonObject) { // List<DynamicCommandMetadata> resultList = new ArrayList<>(); // for (Object currentJSONObject : getJSONArray(jsonObject, COMMANDS_KEY)) { // resultList.add(new DynamicCommandMetadata((JSONObject) currentJSONObject)); // } // return resultList; // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in String type. // */ // private static String getJSONString(JSONObject jsonObject, String key) { // return getJSONObject(jsonObject, key).toString(); // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONArray type. // */ // private static JSONArray getJSONArray(JSONObject jsonObject, String key) { // return (JSONArray) getJSONObject(jsonObject, key); // } // // /** // * Simple getter which transforms the result into the desired type. If the key does not exist, // * throw an exception. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONObject type. // * @throws IllegalArgumentException If the key doesn't exist. // */ // private static Object getJSONObject(JSONObject jsonObject, String key) { // Object result = jsonObject.get(key); // if (result == null) { // throw new IllegalArgumentException( // String.format("A '%s' key must be specified in the JSON definition.", key) // ); // } // return result; // } // // public String getInputPattern() { // return this.inputPattern; // } // // public String getOutputPattern() { // return this.outputPattern; // } // // public List<String> getMatcherOrder() { // return this.matcherOrder; // } // } // Path: src/test/java/com/google/cloud/spanner/pgadapter/MetadataTest.java import com.google.cloud.spanner.pgadapter.metadata.DynamicCommandMetadata; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.junit.Assert; import org.junit.Test; // Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class MetadataTest { @Test public void testDynamicCommandMetadataSingleCommand() throws Exception { String inputJSON = "" + "{" + " \"commands\": " + " [ " + " {" + " \"input_pattern\": \"this is the input SQL query\", " + " \"output_pattern\": \"this is the output SQL query\", " + " \"matcher_array\": []" + " }" + " ]" + "}"; JSONParser parser = new JSONParser();
List<DynamicCommandMetadata> result = DynamicCommandMetadata
cloudspannerecosystem/pgadapter
src/test/java/com/google/cloud/spanner/pgadapter/ConverterTest.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/SQLMetadata.java // public class SQLMetadata { // // private final String sqlString; // private final int parameterCount; // // public SQLMetadata(String sqlString, int totalParameters) { // this.sqlString = sqlString; // this.parameterCount = totalParameters; // } // // public int getParameterCount() { // return this.parameterCount; // } // // public String getSqlString() { // return this.sqlString; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/utils/Converter.java // public class Converter { // // /** // * PostgreSQL parameters occur as $\\d+, whereas JDBC expects a question mark. For now, doing a // * simple iteration to correct. Taking into account both quoted strings and escape sequences. // * // * @param sql The PostgreSQL String. // * @return A {@link SQLMetadata} object containing both the corrected SQL String as well as the // * number of parameters iterated. // */ // public static SQLMetadata toJDBCParams(String sql) { // Preconditions.checkNotNull(sql); // StringBuilder result = new StringBuilder(); // boolean openSingleQuote = false; // boolean openDoubleQuote = false; // boolean openEscape = false; // int parameterCount = 0; // for (int index = 0; index < sql.length(); index++) { // char character = sql.charAt(index); // if (openEscape) { // openEscape = false; // } else if (character == '\"') { // openSingleQuote = !openSingleQuote; // } else if (character == '\'') { // openDoubleQuote = !openDoubleQuote; // } else if (character == '\\') { // openEscape = true; // } else if (!(openDoubleQuote || openSingleQuote) // && character == '$' && index + 1 < sql.length() // && Character.isDigit(sql.charAt(index + 1))) { // parameterCount++; // result.append('?'); // while (++index < sql.length() && Character.isDigit(sql.charAt(index))) { // } // index -= 1; // continue; // } // result.append(character); // } // return new SQLMetadata(result.toString(), parameterCount); // } // // /** // * Try to guess the most appropriate data type of the given value. PostgreSQL uses text format for // * much of the communication, and in some cases it is left to the receiver to guess the type of // * data (generally this is supposed to be handled server-side, but Spanner does not). // * // * @param sql The value to inspect and try to guess the data type of. May not be // * <code>null</code>. // * @return the {@link Oid} constant that is most appropriate for the given value // */ // public static int guessPGDataType(String sql) { // Preconditions.checkNotNull(sql); // if (DateParser.isDate(sql)) { // return Oid.DATE; // } else if (TimestampParser.isTimestamp(sql)) { // return Oid.TIMESTAMP; // } // return Oid.UNSPECIFIED; // } // // /** // * Return the data of the specified column of the {@link ResultSet} as a byte array. The column // * may not contain a null value. // * // * @param result The {@link ResultSet} to read the data from. // * @param metadata The {@link ResultSetMetaData} object holding the metadata for the result. // * @param columnarIndex The columnar index. // * @param format The {@link DataFormat} format to use to encode the data. // * @return a byte array containing the data in the specified format. // */ // public byte[] parseData(ResultSet result, // ResultSetMetaData metadata, // int columnarIndex, // DataFormat format) throws SQLException { // Preconditions.checkArgument(result.getObject(columnarIndex) != null, // "Column may not contain a null value"); // Parser parser = Parser.create(result, metadata.getColumnType(columnarIndex), columnarIndex); // return parser.parse(format); // } // // // }
import com.google.cloud.spanner.pgadapter.metadata.SQLMetadata; import com.google.cloud.spanner.pgadapter.utils.Converter; import org.junit.Assert; import org.junit.Test;
// Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class ConverterTest { @Test public void testToJDBCParams() { String sqlStatement = "SELECT * FROM users WHERE name = $1 AND age > $2 AND age < $123456789"; // Simple case String expectedResult = "SELECT * FROM users WHERE name = ? AND age > ? AND age < ?"; int parameterCount = 3;
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/SQLMetadata.java // public class SQLMetadata { // // private final String sqlString; // private final int parameterCount; // // public SQLMetadata(String sqlString, int totalParameters) { // this.sqlString = sqlString; // this.parameterCount = totalParameters; // } // // public int getParameterCount() { // return this.parameterCount; // } // // public String getSqlString() { // return this.sqlString; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/utils/Converter.java // public class Converter { // // /** // * PostgreSQL parameters occur as $\\d+, whereas JDBC expects a question mark. For now, doing a // * simple iteration to correct. Taking into account both quoted strings and escape sequences. // * // * @param sql The PostgreSQL String. // * @return A {@link SQLMetadata} object containing both the corrected SQL String as well as the // * number of parameters iterated. // */ // public static SQLMetadata toJDBCParams(String sql) { // Preconditions.checkNotNull(sql); // StringBuilder result = new StringBuilder(); // boolean openSingleQuote = false; // boolean openDoubleQuote = false; // boolean openEscape = false; // int parameterCount = 0; // for (int index = 0; index < sql.length(); index++) { // char character = sql.charAt(index); // if (openEscape) { // openEscape = false; // } else if (character == '\"') { // openSingleQuote = !openSingleQuote; // } else if (character == '\'') { // openDoubleQuote = !openDoubleQuote; // } else if (character == '\\') { // openEscape = true; // } else if (!(openDoubleQuote || openSingleQuote) // && character == '$' && index + 1 < sql.length() // && Character.isDigit(sql.charAt(index + 1))) { // parameterCount++; // result.append('?'); // while (++index < sql.length() && Character.isDigit(sql.charAt(index))) { // } // index -= 1; // continue; // } // result.append(character); // } // return new SQLMetadata(result.toString(), parameterCount); // } // // /** // * Try to guess the most appropriate data type of the given value. PostgreSQL uses text format for // * much of the communication, and in some cases it is left to the receiver to guess the type of // * data (generally this is supposed to be handled server-side, but Spanner does not). // * // * @param sql The value to inspect and try to guess the data type of. May not be // * <code>null</code>. // * @return the {@link Oid} constant that is most appropriate for the given value // */ // public static int guessPGDataType(String sql) { // Preconditions.checkNotNull(sql); // if (DateParser.isDate(sql)) { // return Oid.DATE; // } else if (TimestampParser.isTimestamp(sql)) { // return Oid.TIMESTAMP; // } // return Oid.UNSPECIFIED; // } // // /** // * Return the data of the specified column of the {@link ResultSet} as a byte array. The column // * may not contain a null value. // * // * @param result The {@link ResultSet} to read the data from. // * @param metadata The {@link ResultSetMetaData} object holding the metadata for the result. // * @param columnarIndex The columnar index. // * @param format The {@link DataFormat} format to use to encode the data. // * @return a byte array containing the data in the specified format. // */ // public byte[] parseData(ResultSet result, // ResultSetMetaData metadata, // int columnarIndex, // DataFormat format) throws SQLException { // Preconditions.checkArgument(result.getObject(columnarIndex) != null, // "Column may not contain a null value"); // Parser parser = Parser.create(result, metadata.getColumnType(columnarIndex), columnarIndex); // return parser.parse(format); // } // // // } // Path: src/test/java/com/google/cloud/spanner/pgadapter/ConverterTest.java import com.google.cloud.spanner.pgadapter.metadata.SQLMetadata; import com.google.cloud.spanner.pgadapter.utils.Converter; import org.junit.Assert; import org.junit.Test; // Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class ConverterTest { @Test public void testToJDBCParams() { String sqlStatement = "SELECT * FROM users WHERE name = $1 AND age > $2 AND age < $123456789"; // Simple case String expectedResult = "SELECT * FROM users WHERE name = ? AND age > ? AND age < ?"; int parameterCount = 3;
SQLMetadata result = Converter.toJDBCParams(sqlStatement);
cloudspannerecosystem/pgadapter
src/test/java/com/google/cloud/spanner/pgadapter/ConverterTest.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/SQLMetadata.java // public class SQLMetadata { // // private final String sqlString; // private final int parameterCount; // // public SQLMetadata(String sqlString, int totalParameters) { // this.sqlString = sqlString; // this.parameterCount = totalParameters; // } // // public int getParameterCount() { // return this.parameterCount; // } // // public String getSqlString() { // return this.sqlString; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/utils/Converter.java // public class Converter { // // /** // * PostgreSQL parameters occur as $\\d+, whereas JDBC expects a question mark. For now, doing a // * simple iteration to correct. Taking into account both quoted strings and escape sequences. // * // * @param sql The PostgreSQL String. // * @return A {@link SQLMetadata} object containing both the corrected SQL String as well as the // * number of parameters iterated. // */ // public static SQLMetadata toJDBCParams(String sql) { // Preconditions.checkNotNull(sql); // StringBuilder result = new StringBuilder(); // boolean openSingleQuote = false; // boolean openDoubleQuote = false; // boolean openEscape = false; // int parameterCount = 0; // for (int index = 0; index < sql.length(); index++) { // char character = sql.charAt(index); // if (openEscape) { // openEscape = false; // } else if (character == '\"') { // openSingleQuote = !openSingleQuote; // } else if (character == '\'') { // openDoubleQuote = !openDoubleQuote; // } else if (character == '\\') { // openEscape = true; // } else if (!(openDoubleQuote || openSingleQuote) // && character == '$' && index + 1 < sql.length() // && Character.isDigit(sql.charAt(index + 1))) { // parameterCount++; // result.append('?'); // while (++index < sql.length() && Character.isDigit(sql.charAt(index))) { // } // index -= 1; // continue; // } // result.append(character); // } // return new SQLMetadata(result.toString(), parameterCount); // } // // /** // * Try to guess the most appropriate data type of the given value. PostgreSQL uses text format for // * much of the communication, and in some cases it is left to the receiver to guess the type of // * data (generally this is supposed to be handled server-side, but Spanner does not). // * // * @param sql The value to inspect and try to guess the data type of. May not be // * <code>null</code>. // * @return the {@link Oid} constant that is most appropriate for the given value // */ // public static int guessPGDataType(String sql) { // Preconditions.checkNotNull(sql); // if (DateParser.isDate(sql)) { // return Oid.DATE; // } else if (TimestampParser.isTimestamp(sql)) { // return Oid.TIMESTAMP; // } // return Oid.UNSPECIFIED; // } // // /** // * Return the data of the specified column of the {@link ResultSet} as a byte array. The column // * may not contain a null value. // * // * @param result The {@link ResultSet} to read the data from. // * @param metadata The {@link ResultSetMetaData} object holding the metadata for the result. // * @param columnarIndex The columnar index. // * @param format The {@link DataFormat} format to use to encode the data. // * @return a byte array containing the data in the specified format. // */ // public byte[] parseData(ResultSet result, // ResultSetMetaData metadata, // int columnarIndex, // DataFormat format) throws SQLException { // Preconditions.checkArgument(result.getObject(columnarIndex) != null, // "Column may not contain a null value"); // Parser parser = Parser.create(result, metadata.getColumnType(columnarIndex), columnarIndex); // return parser.parse(format); // } // // // }
import com.google.cloud.spanner.pgadapter.metadata.SQLMetadata; import com.google.cloud.spanner.pgadapter.utils.Converter; import org.junit.Assert; import org.junit.Test;
// Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class ConverterTest { @Test public void testToJDBCParams() { String sqlStatement = "SELECT * FROM users WHERE name = $1 AND age > $2 AND age < $123456789"; // Simple case String expectedResult = "SELECT * FROM users WHERE name = ? AND age > ? AND age < ?"; int parameterCount = 3;
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/SQLMetadata.java // public class SQLMetadata { // // private final String sqlString; // private final int parameterCount; // // public SQLMetadata(String sqlString, int totalParameters) { // this.sqlString = sqlString; // this.parameterCount = totalParameters; // } // // public int getParameterCount() { // return this.parameterCount; // } // // public String getSqlString() { // return this.sqlString; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/utils/Converter.java // public class Converter { // // /** // * PostgreSQL parameters occur as $\\d+, whereas JDBC expects a question mark. For now, doing a // * simple iteration to correct. Taking into account both quoted strings and escape sequences. // * // * @param sql The PostgreSQL String. // * @return A {@link SQLMetadata} object containing both the corrected SQL String as well as the // * number of parameters iterated. // */ // public static SQLMetadata toJDBCParams(String sql) { // Preconditions.checkNotNull(sql); // StringBuilder result = new StringBuilder(); // boolean openSingleQuote = false; // boolean openDoubleQuote = false; // boolean openEscape = false; // int parameterCount = 0; // for (int index = 0; index < sql.length(); index++) { // char character = sql.charAt(index); // if (openEscape) { // openEscape = false; // } else if (character == '\"') { // openSingleQuote = !openSingleQuote; // } else if (character == '\'') { // openDoubleQuote = !openDoubleQuote; // } else if (character == '\\') { // openEscape = true; // } else if (!(openDoubleQuote || openSingleQuote) // && character == '$' && index + 1 < sql.length() // && Character.isDigit(sql.charAt(index + 1))) { // parameterCount++; // result.append('?'); // while (++index < sql.length() && Character.isDigit(sql.charAt(index))) { // } // index -= 1; // continue; // } // result.append(character); // } // return new SQLMetadata(result.toString(), parameterCount); // } // // /** // * Try to guess the most appropriate data type of the given value. PostgreSQL uses text format for // * much of the communication, and in some cases it is left to the receiver to guess the type of // * data (generally this is supposed to be handled server-side, but Spanner does not). // * // * @param sql The value to inspect and try to guess the data type of. May not be // * <code>null</code>. // * @return the {@link Oid} constant that is most appropriate for the given value // */ // public static int guessPGDataType(String sql) { // Preconditions.checkNotNull(sql); // if (DateParser.isDate(sql)) { // return Oid.DATE; // } else if (TimestampParser.isTimestamp(sql)) { // return Oid.TIMESTAMP; // } // return Oid.UNSPECIFIED; // } // // /** // * Return the data of the specified column of the {@link ResultSet} as a byte array. The column // * may not contain a null value. // * // * @param result The {@link ResultSet} to read the data from. // * @param metadata The {@link ResultSetMetaData} object holding the metadata for the result. // * @param columnarIndex The columnar index. // * @param format The {@link DataFormat} format to use to encode the data. // * @return a byte array containing the data in the specified format. // */ // public byte[] parseData(ResultSet result, // ResultSetMetaData metadata, // int columnarIndex, // DataFormat format) throws SQLException { // Preconditions.checkArgument(result.getObject(columnarIndex) != null, // "Column may not contain a null value"); // Parser parser = Parser.create(result, metadata.getColumnType(columnarIndex), columnarIndex); // return parser.parse(format); // } // // // } // Path: src/test/java/com/google/cloud/spanner/pgadapter/ConverterTest.java import com.google.cloud.spanner.pgadapter.metadata.SQLMetadata; import com.google.cloud.spanner.pgadapter.utils.Converter; import org.junit.Assert; import org.junit.Test; // Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter; public class ConverterTest { @Test public void testToJDBCParams() { String sqlStatement = "SELECT * FROM users WHERE name = $1 AND age > $2 AND age < $123456789"; // Simple case String expectedResult = "SELECT * FROM users WHERE name = ? AND age > ? AND age < ?"; int parameterCount = 3;
SQLMetadata result = Converter.toJDBCParams(sqlStatement);
cloudspannerecosystem/pgadapter
src/main/java/com/google/cloud/spanner/pgadapter/commands/Command.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DynamicCommandMetadata.java // public class DynamicCommandMetadata { // // private static final String COMMANDS_KEY = "commands"; // private static final String INPUT_KEY = "input_pattern"; // private static final String OUTPUT_KEY = "output_pattern"; // private static final String MATCHER_KEY = "matcher_array"; // // private String inputPattern; // private String outputPattern; // private List<String> matcherOrder; // // private DynamicCommandMetadata(JSONObject commandJSON) { // this.inputPattern = getJSONString(commandJSON, INPUT_KEY); // this.outputPattern = getJSONString(commandJSON, OUTPUT_KEY); // this.matcherOrder = new ArrayList<>(); // for (Object arrayObject : getJSONArray(commandJSON, MATCHER_KEY)) { // String argumentNumber = (String) arrayObject; // this.matcherOrder.add(argumentNumber); // } // } // // /** // * Takes a JSON object and returns a list of metadata objects holding the desired information. // * // * @param jsonObject Input JSON object in the format {"commands": [{"input_pattern": "", // * "output_pattern": "", "matcher_array": [number1, ...]}, ...]} // * @return A list of constructed metadata objects in the format understood by DynamicCommands // */ // public static List<DynamicCommandMetadata> fromJSON(JSONObject jsonObject) { // List<DynamicCommandMetadata> resultList = new ArrayList<>(); // for (Object currentJSONObject : getJSONArray(jsonObject, COMMANDS_KEY)) { // resultList.add(new DynamicCommandMetadata((JSONObject) currentJSONObject)); // } // return resultList; // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in String type. // */ // private static String getJSONString(JSONObject jsonObject, String key) { // return getJSONObject(jsonObject, key).toString(); // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONArray type. // */ // private static JSONArray getJSONArray(JSONObject jsonObject, String key) { // return (JSONArray) getJSONObject(jsonObject, key); // } // // /** // * Simple getter which transforms the result into the desired type. If the key does not exist, // * throw an exception. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONObject type. // * @throws IllegalArgumentException If the key doesn't exist. // */ // private static Object getJSONObject(JSONObject jsonObject, String key) { // Object result = jsonObject.get(key); // if (result == null) { // throw new IllegalArgumentException( // String.format("A '%s' key must be specified in the JSON definition.", key) // ); // } // return result; // } // // public String getInputPattern() { // return this.inputPattern; // } // // public String getOutputPattern() { // return this.outputPattern; // } // // public List<String> getMatcherOrder() { // return this.matcherOrder; // } // }
import com.google.cloud.spanner.pgadapter.metadata.DynamicCommandMetadata; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.simple.JSONObject;
// Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter.commands; /** * This abstract class concerns itself with representing a method of matching a specific statement * and translating it to a form that Spanner understands. The user should call is() to determine * whether it matches before trying to translate. */ abstract public class Command { protected Matcher matcher; protected String sql; public Command(String sql) { this.sql = sql; this.matcher = getPattern().matcher(sql); } /** * This constructor should only be called if you do wish to do your own matching (i.e.: set up * this.matcher). Useful if the pattern is not static, or not pattern related (in which case you * may set it to null). */ protected Command(Matcher matcher) { this.matcher = matcher; } /** * The list of all subcommands to this command. When subclassing this, make sure to add the new * command to the below list, if applicable (i.e.: if you want it to be run). Commands may also be * specified via Dynamic Commands, which are defined from an input JSON file. These commands * precede the hard-coded ones in execution. * * @param sql The SQL command to be translated. * @param connection The connection currently in use. * @return A list of all Command subclasses. */ public static List<Command> getCommands(String sql, Connection connection, JSONObject commandMetadataJSON) { List<Command> commandList = new ArrayList<>();
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DynamicCommandMetadata.java // public class DynamicCommandMetadata { // // private static final String COMMANDS_KEY = "commands"; // private static final String INPUT_KEY = "input_pattern"; // private static final String OUTPUT_KEY = "output_pattern"; // private static final String MATCHER_KEY = "matcher_array"; // // private String inputPattern; // private String outputPattern; // private List<String> matcherOrder; // // private DynamicCommandMetadata(JSONObject commandJSON) { // this.inputPattern = getJSONString(commandJSON, INPUT_KEY); // this.outputPattern = getJSONString(commandJSON, OUTPUT_KEY); // this.matcherOrder = new ArrayList<>(); // for (Object arrayObject : getJSONArray(commandJSON, MATCHER_KEY)) { // String argumentNumber = (String) arrayObject; // this.matcherOrder.add(argumentNumber); // } // } // // /** // * Takes a JSON object and returns a list of metadata objects holding the desired information. // * // * @param jsonObject Input JSON object in the format {"commands": [{"input_pattern": "", // * "output_pattern": "", "matcher_array": [number1, ...]}, ...]} // * @return A list of constructed metadata objects in the format understood by DynamicCommands // */ // public static List<DynamicCommandMetadata> fromJSON(JSONObject jsonObject) { // List<DynamicCommandMetadata> resultList = new ArrayList<>(); // for (Object currentJSONObject : getJSONArray(jsonObject, COMMANDS_KEY)) { // resultList.add(new DynamicCommandMetadata((JSONObject) currentJSONObject)); // } // return resultList; // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in String type. // */ // private static String getJSONString(JSONObject jsonObject, String key) { // return getJSONObject(jsonObject, key).toString(); // } // // /** // * Simple getter which transforms the result into the desired type. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONArray type. // */ // private static JSONArray getJSONArray(JSONObject jsonObject, String key) { // return (JSONArray) getJSONObject(jsonObject, key); // } // // /** // * Simple getter which transforms the result into the desired type. If the key does not exist, // * throw an exception. // * // * @param jsonObject The input object. // * @param key The reference key. // * @return The JSON value referenced by the key in JSONObject type. // * @throws IllegalArgumentException If the key doesn't exist. // */ // private static Object getJSONObject(JSONObject jsonObject, String key) { // Object result = jsonObject.get(key); // if (result == null) { // throw new IllegalArgumentException( // String.format("A '%s' key must be specified in the JSON definition.", key) // ); // } // return result; // } // // public String getInputPattern() { // return this.inputPattern; // } // // public String getOutputPattern() { // return this.outputPattern; // } // // public List<String> getMatcherOrder() { // return this.matcherOrder; // } // } // Path: src/main/java/com/google/cloud/spanner/pgadapter/commands/Command.java import com.google.cloud.spanner.pgadapter.metadata.DynamicCommandMetadata; import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.simple.JSONObject; // Copyright 2020 Google LLC // // 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.google.cloud.spanner.pgadapter.commands; /** * This abstract class concerns itself with representing a method of matching a specific statement * and translating it to a form that Spanner understands. The user should call is() to determine * whether it matches before trying to translate. */ abstract public class Command { protected Matcher matcher; protected String sql; public Command(String sql) { this.sql = sql; this.matcher = getPattern().matcher(sql); } /** * This constructor should only be called if you do wish to do your own matching (i.e.: set up * this.matcher). Useful if the pattern is not static, or not pattern related (in which case you * may set it to null). */ protected Command(Matcher matcher) { this.matcher = matcher; } /** * The list of all subcommands to this command. When subclassing this, make sure to add the new * command to the below list, if applicable (i.e.: if you want it to be run). Commands may also be * specified via Dynamic Commands, which are defined from an input JSON file. These commands * precede the hard-coded ones in execution. * * @param sql The SQL command to be translated. * @param connection The connection currently in use. * @return A list of all Command subclasses. */ public static List<Command> getCommands(String sql, Connection connection, JSONObject commandMetadataJSON) { List<Command> commandList = new ArrayList<>();
for (DynamicCommandMetadata currentMetadata : DynamicCommandMetadata
cloudspannerecosystem/pgadapter
src/main/java/com/google/cloud/spanner/pgadapter/parsers/Parser.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/ProxyServer.java // public enum DataFormat { // /** // * Data is returned to the client in binary form. This is the most compact format, but it is not // * supported by all clients for all data types. Only when the client specifically requests that // * the data should be returned in binary format, will the server do so. // */ // POSTGRESQL_BINARY((short) 1), // /** // * The default format. Data is returned to the client in a format that PostgreSQL clients should // * be able to understand and stringParse. Use this format if you are using the {@link Server} // * with a client that tries to interpret the data that is returned by the server, such as for // * example the PostgreSQL JDBC driver. // */ // POSTGRESQL_TEXT((short) 0), // /** // * Data is returned to the client in Cloud Spanner format. Use this format if you are using the // * server with a text-only client, such as psql, that does not try to interpret and stringParse // * the data that is returned. // */ // SPANNER((short) 0); // // /** // * The internal code used by the PostgreSQL wire protocol to determine whether the data should // * be interpreted as text or binary. // */ // private final short code; // // DataFormat(short code) { // this.code = code; // } // // public static DataFormat getDataFormat(int index, // IntermediateStatement statement, // QueryMode mode, // OptionsMetadata options) { // if (options.isBinaryFormat()) { // return DataFormat.POSTGRESQL_BINARY; // } // if (mode == QueryMode.SIMPLE) { // // Simple query mode is always text. // return DataFormat.fromTextFormat(options.getTextFormat()); // } else { // return DataFormat.byCode(statement.getResultFormatCode(index), options.getTextFormat()); // } // } // // public static DataFormat fromTextFormat(TextFormat textFormat) { // switch (textFormat) { // case POSTGRESQL: // return POSTGRESQL_TEXT; // case SPANNER: // return DataFormat.SPANNER; // default: // throw new IllegalArgumentException(); // } // } // // public static DataFormat byCode(short code, TextFormat textFormat) { // return code == 0 ? fromTextFormat(textFormat) : POSTGRESQL_BINARY; // } // // public short getCode() { // return code; // } // }
import com.google.cloud.spanner.pgadapter.ProxyServer.DataFormat; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.postgresql.core.Oid; import org.postgresql.util.ByteConverter;
result = new byte[1]; ByteConverter.bool(result, 0, (Boolean) candidate); return result; case Types.INTEGER: result = new byte[4]; ByteConverter.int4(result, 0, (Integer) candidate); return result; case Types.DOUBLE: result = new byte[8]; ByteConverter.float8(result, 0, (Double) candidate); return result; case Types.BIGINT: result = new byte[8]; ByteConverter.int8(result, 0, (Long) candidate); return result; default: throw new IllegalArgumentException("Type " + type + " is not valid!"); } } public T getItem() { return this.item; } /** * Parses data based on specified data format (Spanner, text, or binary) * * @param format One of possible {@link DataFormat} types to parse data. * @return Byte format version of the input object. */
// Path: src/main/java/com/google/cloud/spanner/pgadapter/ProxyServer.java // public enum DataFormat { // /** // * Data is returned to the client in binary form. This is the most compact format, but it is not // * supported by all clients for all data types. Only when the client specifically requests that // * the data should be returned in binary format, will the server do so. // */ // POSTGRESQL_BINARY((short) 1), // /** // * The default format. Data is returned to the client in a format that PostgreSQL clients should // * be able to understand and stringParse. Use this format if you are using the {@link Server} // * with a client that tries to interpret the data that is returned by the server, such as for // * example the PostgreSQL JDBC driver. // */ // POSTGRESQL_TEXT((short) 0), // /** // * Data is returned to the client in Cloud Spanner format. Use this format if you are using the // * server with a text-only client, such as psql, that does not try to interpret and stringParse // * the data that is returned. // */ // SPANNER((short) 0); // // /** // * The internal code used by the PostgreSQL wire protocol to determine whether the data should // * be interpreted as text or binary. // */ // private final short code; // // DataFormat(short code) { // this.code = code; // } // // public static DataFormat getDataFormat(int index, // IntermediateStatement statement, // QueryMode mode, // OptionsMetadata options) { // if (options.isBinaryFormat()) { // return DataFormat.POSTGRESQL_BINARY; // } // if (mode == QueryMode.SIMPLE) { // // Simple query mode is always text. // return DataFormat.fromTextFormat(options.getTextFormat()); // } else { // return DataFormat.byCode(statement.getResultFormatCode(index), options.getTextFormat()); // } // } // // public static DataFormat fromTextFormat(TextFormat textFormat) { // switch (textFormat) { // case POSTGRESQL: // return POSTGRESQL_TEXT; // case SPANNER: // return DataFormat.SPANNER; // default: // throw new IllegalArgumentException(); // } // } // // public static DataFormat byCode(short code, TextFormat textFormat) { // return code == 0 ? fromTextFormat(textFormat) : POSTGRESQL_BINARY; // } // // public short getCode() { // return code; // } // } // Path: src/main/java/com/google/cloud/spanner/pgadapter/parsers/Parser.java import com.google.cloud.spanner.pgadapter.ProxyServer.DataFormat; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.postgresql.core.Oid; import org.postgresql.util.ByteConverter; result = new byte[1]; ByteConverter.bool(result, 0, (Boolean) candidate); return result; case Types.INTEGER: result = new byte[4]; ByteConverter.int4(result, 0, (Integer) candidate); return result; case Types.DOUBLE: result = new byte[8]; ByteConverter.float8(result, 0, (Double) candidate); return result; case Types.BIGINT: result = new byte[8]; ByteConverter.int8(result, 0, (Long) candidate); return result; default: throw new IllegalArgumentException("Type " + type + " is not valid!"); } } public T getItem() { return this.item; } /** * Parses data based on specified data format (Spanner, text, or binary) * * @param format One of possible {@link DataFormat} types to parse data. * @return Byte format version of the input object. */
public byte[] parse(DataFormat format) {
cloudspannerecosystem/pgadapter
src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediateStatement.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // }
import com.google.cloud.spanner.jdbc.JdbcConstants; import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.common.base.Preconditions; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Logger;
/** * Clean up and save metadata when an exception occurs. * * @param e The exception to store. */ protected void handleExecutionException(SQLException e) { this.exception = e; this.hasMoreData = false; this.statementResult = null; this.resultType = ResultType.NO_RESULT; } /** * Execute the SQL statement, storing metadata. */ public void execute() { this.executed = true; try { this.statement.execute(this.sql); this.executeHelper(); } catch (SQLException e) { handleExecutionException(e); } } /** * Moreso meant for inherited classes, allows one to call describe on a statement. Since raw * statements cannot be described, throw an error. */
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // } // Path: src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediateStatement.java import com.google.cloud.spanner.jdbc.JdbcConstants; import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.common.base.Preconditions; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Logger; /** * Clean up and save metadata when an exception occurs. * * @param e The exception to store. */ protected void handleExecutionException(SQLException e) { this.exception = e; this.hasMoreData = false; this.statementResult = null; this.resultType = ResultType.NO_RESULT; } /** * Execute the SQL statement, storing metadata. */ public void execute() { this.executed = true; try { this.statement.execute(this.sql); this.executeHelper(); } catch (SQLException e) { handleExecutionException(e); } } /** * Moreso meant for inherited classes, allows one to call describe on a statement. Since raw * statements cannot be described, throw an error. */
public DescribeMetadata describe() throws Exception {
cloudspannerecosystem/pgadapter
src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediatePortalStatement.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribePortalMetadata.java // public class DescribePortalMetadata extends DescribeMetadata<ResultSetMetaData> { // // public DescribePortalMetadata(ResultSetMetaData metadata) { // this.metadata = metadata; // } // }
import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.cloud.spanner.pgadapter.metadata.DescribePortalMetadata; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
public short getParameterFormatCode(int index) { if (this.parameterFormatCodes.size() == 0) { return 0; } else if (this.parameterFormatCodes.size() == 1) { return this.parameterFormatCodes.get(0); } else { return this.parameterFormatCodes.get(index - 1); } } @Override public short getResultFormatCode(int index) { if (this.resultFormatCodes == null || this.resultFormatCodes.isEmpty()) { return 0; } else if (this.resultFormatCodes.size() == 1) { return this.resultFormatCodes.get(0); } else { return this.resultFormatCodes.get(index - 1); } } public void setParameterFormatCodes(List<Short> parameterFormatCodes) { this.parameterFormatCodes = parameterFormatCodes; } public void setResultFormatCodes(List<Short> resultFormatCodes) { this.resultFormatCodes = resultFormatCodes; } @Override
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribePortalMetadata.java // public class DescribePortalMetadata extends DescribeMetadata<ResultSetMetaData> { // // public DescribePortalMetadata(ResultSetMetaData metadata) { // this.metadata = metadata; // } // } // Path: src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediatePortalStatement.java import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.cloud.spanner.pgadapter.metadata.DescribePortalMetadata; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public short getParameterFormatCode(int index) { if (this.parameterFormatCodes.size() == 0) { return 0; } else if (this.parameterFormatCodes.size() == 1) { return this.parameterFormatCodes.get(0); } else { return this.parameterFormatCodes.get(index - 1); } } @Override public short getResultFormatCode(int index) { if (this.resultFormatCodes == null || this.resultFormatCodes.isEmpty()) { return 0; } else if (this.resultFormatCodes.size() == 1) { return this.resultFormatCodes.get(0); } else { return this.resultFormatCodes.get(index - 1); } } public void setParameterFormatCodes(List<Short> parameterFormatCodes) { this.parameterFormatCodes = parameterFormatCodes; } public void setResultFormatCodes(List<Short> resultFormatCodes) { this.resultFormatCodes = resultFormatCodes; } @Override
public DescribeMetadata describe() throws Exception {
cloudspannerecosystem/pgadapter
src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediatePortalStatement.java
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribePortalMetadata.java // public class DescribePortalMetadata extends DescribeMetadata<ResultSetMetaData> { // // public DescribePortalMetadata(ResultSetMetaData metadata) { // this.metadata = metadata; // } // }
import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.cloud.spanner.pgadapter.metadata.DescribePortalMetadata; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;
} else if (this.parameterFormatCodes.size() == 1) { return this.parameterFormatCodes.get(0); } else { return this.parameterFormatCodes.get(index - 1); } } @Override public short getResultFormatCode(int index) { if (this.resultFormatCodes == null || this.resultFormatCodes.isEmpty()) { return 0; } else if (this.resultFormatCodes.size() == 1) { return this.resultFormatCodes.get(0); } else { return this.resultFormatCodes.get(index - 1); } } public void setParameterFormatCodes(List<Short> parameterFormatCodes) { this.parameterFormatCodes = parameterFormatCodes; } public void setResultFormatCodes(List<Short> resultFormatCodes) { this.resultFormatCodes = resultFormatCodes; } @Override public DescribeMetadata describe() throws Exception { try { ResultSetMetaData metaData = ((PreparedStatement) this.statement).getMetaData();
// Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribeMetadata.java // public abstract class DescribeMetadata<T> { // // protected T metadata; // // public T getMetadata() { // return this.metadata; // } // } // // Path: src/main/java/com/google/cloud/spanner/pgadapter/metadata/DescribePortalMetadata.java // public class DescribePortalMetadata extends DescribeMetadata<ResultSetMetaData> { // // public DescribePortalMetadata(ResultSetMetaData metadata) { // this.metadata = metadata; // } // } // Path: src/main/java/com/google/cloud/spanner/pgadapter/statements/IntermediatePortalStatement.java import com.google.cloud.spanner.pgadapter.metadata.DescribeMetadata; import com.google.cloud.spanner.pgadapter.metadata.DescribePortalMetadata; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; } else if (this.parameterFormatCodes.size() == 1) { return this.parameterFormatCodes.get(0); } else { return this.parameterFormatCodes.get(index - 1); } } @Override public short getResultFormatCode(int index) { if (this.resultFormatCodes == null || this.resultFormatCodes.isEmpty()) { return 0; } else if (this.resultFormatCodes.size() == 1) { return this.resultFormatCodes.get(0); } else { return this.resultFormatCodes.get(index - 1); } } public void setParameterFormatCodes(List<Short> parameterFormatCodes) { this.parameterFormatCodes = parameterFormatCodes; } public void setResultFormatCodes(List<Short> resultFormatCodes) { this.resultFormatCodes = resultFormatCodes; } @Override public DescribeMetadata describe() throws Exception { try { ResultSetMetaData metaData = ((PreparedStatement) this.statement).getMetaData();
return new DescribePortalMetadata(metaData);
fwix/java-gearman
src/org/gearman/GearmanServer.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // }
import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler;
package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // } // Path: src/org/gearman/GearmanServer.java import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler; package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */
public <X> void openPort(final int port, final GearmanCodec<X> codec) throws IOException;
fwix/java-gearman
src/org/gearman/GearmanServer.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // }
import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler;
package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */ public <X> void openPort(final int port, final GearmanCodec<X> codec) throws IOException; /** * Attempts to close a port that this GearmanServer is listening on. * @param port * The port to close * @return * <code>true</code> if and only if the this GearmanServer secedes at closing * the given port number */ public boolean closePort(final int port); /** * Closes all ports currently opened by this GearmanServer */ public void closeAllPorts(); /** * Returns a set of Integers representing the all of the open ports * @return * a set of Integers representing the all of the open ports */ public Set<Integer> getOpenPorts(); /** * Returns a local connection to this GearmanServer * @return * A local connection to this GearmanServer */
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // } // Path: src/org/gearman/GearmanServer.java import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler; package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */ public <X> void openPort(final int port, final GearmanCodec<X> codec) throws IOException; /** * Attempts to close a port that this GearmanServer is listening on. * @param port * The port to close * @return * <code>true</code> if and only if the this GearmanServer secedes at closing * the given port number */ public boolean closePort(final int port); /** * Closes all ports currently opened by this GearmanServer */ public void closeAllPorts(); /** * Returns a set of Integers representing the all of the open ports * @return * a set of Integers representing the all of the open ports */ public Set<Integer> getOpenPorts(); /** * Returns a local connection to this GearmanServer * @return * A local connection to this GearmanServer */
public <A> void createGearmanConnection(GearmanConnectionHandler<A> handler, GearmanCallbackHandler<GearmanServer, ConnectCallbackResult> failHandler);
fwix/java-gearman
src/org/gearman/GearmanServer.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // }
import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler;
package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */ public <X> void openPort(final int port, final GearmanCodec<X> codec) throws IOException; /** * Attempts to close a port that this GearmanServer is listening on. * @param port * The port to close * @return * <code>true</code> if and only if the this GearmanServer secedes at closing * the given port number */ public boolean closePort(final int port); /** * Closes all ports currently opened by this GearmanServer */ public void closeAllPorts(); /** * Returns a set of Integers representing the all of the open ports * @return * a set of Integers representing the all of the open ports */ public Set<Integer> getOpenPorts(); /** * Returns a local connection to this GearmanServer * @return * A local connection to this GearmanServer */
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // // Path: src/org/gearman/core/GearmanCodec.java // public interface GearmanCodec<X> { // public void init(GearmanCodecChannel<X> channel); // public ByteBuffer createByteBuffer(); // public void decode(GearmanCodecChannel<X> channel, int byteCount); // public byte[] encode(GearmanPacket packet); // } // // Path: src/org/gearman/core/GearmanConnectionHandler.java // public interface GearmanConnectionHandler<X> { // public void onAccept(GearmanConnection<X> conn); // public void onPacketReceived(GearmanPacket packet, GearmanConnection<X> conn); // public void onDisconnect(GearmanConnection<X> conn); // } // Path: src/org/gearman/GearmanServer.java import java.io.IOException; import java.util.Set; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; import org.gearman.core.GearmanCodec; import org.gearman.core.GearmanConnectionHandler; package org.gearman; public interface GearmanServer extends GearmanService { public static enum ConnectCallbackResult implements GearmanCallbackResult{ SERVER_SHUTDOWN; @Override public boolean isSuccessful() { return false; } } /** * Attempts to open the default port to listen on * @throws IOException * thrown if opening the port fails */ public void openPort() throws IOException; /** * Attempts to open and listen on a given port. * @param port * The port to open * @throws IOException * thrown if opening the port fails */ public void openPort(final int port) throws IOException; /** * Attempts to open and listen on a given port.<br> * <br> * Allows the user specifies the GearmanCodec used on this port. * @param port * The port to open * @param codec * The codec to use for encoding and decoding GearmanPackets * @throws IOException * thrown if opening the port fails */ public <X> void openPort(final int port, final GearmanCodec<X> codec) throws IOException; /** * Attempts to close a port that this GearmanServer is listening on. * @param port * The port to close * @return * <code>true</code> if and only if the this GearmanServer secedes at closing * the given port number */ public boolean closePort(final int port); /** * Closes all ports currently opened by this GearmanServer */ public void closeAllPorts(); /** * Returns a set of Integers representing the all of the open ports * @return * a set of Integers representing the all of the open ports */ public Set<Integer> getOpenPorts(); /** * Returns a local connection to this GearmanServer * @return * A local connection to this GearmanServer */
public <A> void createGearmanConnection(GearmanConnectionHandler<A> handler, GearmanCallbackHandler<GearmanServer, ConnectCallbackResult> failHandler);
fwix/java-gearman
src/org/gearman/ClientJobSubmission.java
// Path: src/org/gearman/GearmanClient.java // public static enum SubmitCallbackResult implements GearmanCallbackResult{ // // /** // * The job was sucessfuly submitted to a job server // */ // SUBMIT_SUCCESSFUL, // // /** // * Failed to send the job due to there being no job servers to // * submit to. // */ // FAILED_TO_NO_SERVER, // // /** // * // */ // FAILED_TO_CONNECT, // // /** // * The job has already been submitted to a client and has not yet completed // */ // FAILED_TO_INVALID_JOB_STATE, // // /** // * The {@link GearmanClient} is shutdown // */ // FAILED_TO_SHUTDOWN; // // @Override // public boolean isSuccessful() { // return this==SUBMIT_SUCCESSFUL; // } // // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // }
import org.gearman.GearmanClient.SubmitCallbackResult; import org.gearman.core.GearmanCallbackHandler;
package org.gearman; class ClientJobSubmission { public final GearmanJob job;
// Path: src/org/gearman/GearmanClient.java // public static enum SubmitCallbackResult implements GearmanCallbackResult{ // // /** // * The job was sucessfuly submitted to a job server // */ // SUBMIT_SUCCESSFUL, // // /** // * Failed to send the job due to there being no job servers to // * submit to. // */ // FAILED_TO_NO_SERVER, // // /** // * // */ // FAILED_TO_CONNECT, // // /** // * The job has already been submitted to a client and has not yet completed // */ // FAILED_TO_INVALID_JOB_STATE, // // /** // * The {@link GearmanClient} is shutdown // */ // FAILED_TO_SHUTDOWN; // // @Override // public boolean isSuccessful() { // return this==SUBMIT_SUCCESSFUL; // } // // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // Path: src/org/gearman/ClientJobSubmission.java import org.gearman.GearmanClient.SubmitCallbackResult; import org.gearman.core.GearmanCallbackHandler; package org.gearman; class ClientJobSubmission { public final GearmanJob job;
public final GearmanCallbackHandler<GearmanJob, SubmitCallbackResult> callback;
fwix/java-gearman
src/org/gearman/ClientJobSubmission.java
// Path: src/org/gearman/GearmanClient.java // public static enum SubmitCallbackResult implements GearmanCallbackResult{ // // /** // * The job was sucessfuly submitted to a job server // */ // SUBMIT_SUCCESSFUL, // // /** // * Failed to send the job due to there being no job servers to // * submit to. // */ // FAILED_TO_NO_SERVER, // // /** // * // */ // FAILED_TO_CONNECT, // // /** // * The job has already been submitted to a client and has not yet completed // */ // FAILED_TO_INVALID_JOB_STATE, // // /** // * The {@link GearmanClient} is shutdown // */ // FAILED_TO_SHUTDOWN; // // @Override // public boolean isSuccessful() { // return this==SUBMIT_SUCCESSFUL; // } // // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // }
import org.gearman.GearmanClient.SubmitCallbackResult; import org.gearman.core.GearmanCallbackHandler;
package org.gearman; class ClientJobSubmission { public final GearmanJob job;
// Path: src/org/gearman/GearmanClient.java // public static enum SubmitCallbackResult implements GearmanCallbackResult{ // // /** // * The job was sucessfuly submitted to a job server // */ // SUBMIT_SUCCESSFUL, // // /** // * Failed to send the job due to there being no job servers to // * submit to. // */ // FAILED_TO_NO_SERVER, // // /** // * // */ // FAILED_TO_CONNECT, // // /** // * The job has already been submitted to a client and has not yet completed // */ // FAILED_TO_INVALID_JOB_STATE, // // /** // * The {@link GearmanClient} is shutdown // */ // FAILED_TO_SHUTDOWN; // // @Override // public boolean isSuccessful() { // return this==SUBMIT_SUCCESSFUL; // } // // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // Path: src/org/gearman/ClientJobSubmission.java import org.gearman.GearmanClient.SubmitCallbackResult; import org.gearman.core.GearmanCallbackHandler; package org.gearman; class ClientJobSubmission { public final GearmanJob job;
public final GearmanCallbackHandler<GearmanJob, SubmitCallbackResult> callback;
fwix/java-gearman
src/org/gearman/MultiServerFunction.java
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // }
import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray;
} public void removeJobs(){ high.removeJobs(); medium.removeJobs(); low.removeJobs(); } public void addNoopable(final ServerClient noopable) { high.addNoopable(noopable); medium.addNoopable(noopable); low.addNoopable(noopable); } public void removeNoopable(final ServerClient noopable){ high.removeNoopable(noopable); medium.removeNoopable(noopable); low.removeNoopable(noopable); } public void setMaxQueue(final int size){ high.setMaxQueue(size); medium.setMaxQueue(size); low.setMaxQueue(size); }
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // Path: src/org/gearman/MultiServerFunction.java import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray; } public void removeJobs(){ high.removeJobs(); medium.removeJobs(); low.removeJobs(); } public void addNoopable(final ServerClient noopable) { high.addNoopable(noopable); medium.addNoopable(noopable); low.addNoopable(noopable); } public void removeNoopable(final ServerClient noopable){ high.removeNoopable(noopable); medium.removeNoopable(noopable); low.removeNoopable(noopable); } public void setMaxQueue(final int size){ high.setMaxQueue(size); medium.setMaxQueue(size); low.setMaxQueue(size); }
public ByteArray getName(){
fwix/java-gearman
src/org/gearman/MultiServerFunction.java
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // }
import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray;
medium.addNoopable(noopable); low.addNoopable(noopable); } public void removeNoopable(final ServerClient noopable){ high.removeNoopable(noopable); medium.removeNoopable(noopable); low.removeNoopable(noopable); } public void setMaxQueue(final int size){ high.setMaxQueue(size); medium.setMaxQueue(size); low.setMaxQueue(size); } public ByteArray getName(){ return high.getName(); } public boolean queueIsEmpty(){ return high.queueIsEmpty() && medium.queueIsEmpty() && low.queueIsEmpty(); }
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // Path: src/org/gearman/MultiServerFunction.java import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray; medium.addNoopable(noopable); low.addNoopable(noopable); } public void removeNoopable(final ServerClient noopable){ high.removeNoopable(noopable); medium.removeNoopable(noopable); low.removeNoopable(noopable); } public void setMaxQueue(final int size){ high.setMaxQueue(size); medium.setMaxQueue(size); low.setMaxQueue(size); } public ByteArray getName(){ return high.getName(); } public boolean queueIsEmpty(){ return high.queueIsEmpty() && medium.queueIsEmpty() && low.queueIsEmpty(); }
public void createJob(final ByteArray uniqueID, final byte[] data, final JobPriority priority, final ServerClient creator, boolean isBackground){
fwix/java-gearman
src/org/gearman/WorkerImpl.java
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // };
import java.net.InetSocketAddress; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds;
default: assert false; } } } } private class LocalConnectionController extends WorkerConnectionController<GearmanServer, org.gearman.GearmanServer.ConnectCallbackResult> { LocalConnectionController(GearmanServer key) { super(WorkerImpl.this, key); } @Override protected WorkerDispatcher getDispatcher() { return WorkerImpl.this.dispatcher; } @Override protected WorkerImpl getWorker() { return WorkerImpl.this; } @Override protected void onConnect(ControllerState oldState) { super.getKey().createGearmanConnection(this, this); } @Override
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // Path: src/org/gearman/WorkerImpl.java import java.net.InetSocketAddress; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; default: assert false; } } } } private class LocalConnectionController extends WorkerConnectionController<GearmanServer, org.gearman.GearmanServer.ConnectCallbackResult> { LocalConnectionController(GearmanServer key) { super(WorkerImpl.this, key); } @Override protected WorkerDispatcher getDispatcher() { return WorkerImpl.this.dispatcher; } @Override protected WorkerImpl getWorker() { return WorkerImpl.this; } @Override protected void onConnect(ControllerState oldState) { super.getKey().createGearmanConnection(this, this); } @Override
protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) {
fwix/java-gearman
src/org/gearman/WorkerImpl.java
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // };
import java.net.InetSocketAddress; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds;
RemoteConnectionController(InetSocketAddress key) { super(WorkerImpl.this, key); } @Override public void onOpen(ControllerState oldState) { if(WorkerImpl.this.funcMap.isEmpty()) { super.closeServer(); } else { super.onOpen(oldState); } } @Override protected WorkerDispatcher getDispatcher() { return WorkerImpl.this.dispatcher; } @Override protected WorkerImpl getWorker() { return WorkerImpl.this; } @Override protected void onConnect(ControllerState oldState) { gearman.getGearmanConnectionManager().createGearmanConnection(super.getKey(), this, this); } @Override protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) {
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // Path: src/org/gearman/WorkerImpl.java import java.net.InetSocketAddress; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; RemoteConnectionController(InetSocketAddress key) { super(WorkerImpl.this, key); } @Override public void onOpen(ControllerState oldState) { if(WorkerImpl.this.funcMap.isEmpty()) { super.closeServer(); } else { super.onOpen(oldState); } } @Override protected WorkerDispatcher getDispatcher() { return WorkerImpl.this.dispatcher; } @Override protected WorkerImpl getWorker() { return WorkerImpl.this; } @Override protected void onConnect(ControllerState oldState) { gearman.getGearmanConnectionManager().createGearmanConnection(super.getKey(), this, this); } @Override protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) {
Action action = null;
fwix/java-gearman
src/org/gearman/core/StandardCodec.java
// Path: src/org/gearman/core/GearmanPacket.java // public static enum Magic { // /** // * A request packet is sent to the server to request a service.<br> // * Magic code = "\0REQ" = 5391697 // */ // REQ(5391697), // // /** // * A response packet is sent from the server to a client or worker as a response // * from handling a request.<br> // * Magic code = "\0RES" = 5391699 // */ // RES(5391699); // // /** The magic number */ // private final int code; // // private Magic(int code) { // this.code = code; // } // // /** // * Returns the magic code // * @return // * The magic code. // */ // public final int getMagicCode() { // return code; // } // // /** // * Gets the <code>Magic</code> enumerator based on the magic code // * @param code // * The magic code. // * @return // * The Magic object. If the code is invalid, null is returned // */ // public static final Magic fromMagicCode(final int code) { // switch(code) { // case 5391697: // return REQ; // case 5391699: // return RES; // default: // return null; // } // } // } // // Path: src/org/gearman/core/GearmanPacket.java // public static enum Type{ // TEXT(0,1), CAN_DO(1,1), CANT_DO(2,1), RESET_ABILITIES(3,0), PRE_SLEEP(4,0), UNUSED(5,0), // NOOP(6,0), SUBMIT_JOB(7,3), JOB_CREATED(8,1), GRAB_JOB(9,0), NO_JOB(10,0), JOB_ASSIGN(11,3), // WORK_STATUS(12, 3), WORK_COMPLETE(13,2), WORK_FAIL(14,1), GET_STATUS(15,1), ECHO_REQ(16,1), // ECHO_RES(17,1), SUBMIT_JOB_BG(18,3), ERROR(19, 2), STATUS_RES(20, 5), SUBMIT_JOB_HIGH(21,3), // SET_CLIENT_ID(22,1), CAN_DO_TIMEOUT(23,2), ALL_YOURS(24,0), WORK_EXCEPTION(25,2), // OPTION_REQ(26,1), OPTION_RES(27,1), WORK_DATA(28,2), WORK_WARNING(29, 2), GRAB_JOB_UNIQ(30,0), // JOB_ASSIGN_UNIQ(31,4), SUBMIT_JOB_HIGH_BG(32,3), SUBMIT_JOB_LOW(33,3), SUBMIT_JOB_LOW_BG(34,3), // SUBMIT_JOB_SCHED(35,8), SUBMIT_JOB_EPOCH(36,4); // // private final int type; // private final int args; // private Type(final int type, final int args) { // this.type = type; // this.args = args; // } // // public final int getTypeValue() { // return type; // } // public final int getArgumentCount() { // return args; // } // // public static final Type fromTypeValue(final int value) { // switch(value) { // case(0): return TEXT; case(1): return CAN_DO; case(2): return CANT_DO; // case(3): return RESET_ABILITIES; case(4): return PRE_SLEEP; case(5): return UNUSED; // case(6): return NOOP; case(7): return SUBMIT_JOB; case(8): return JOB_CREATED; // case(9): return GRAB_JOB; case(10): return NO_JOB; case(11): return JOB_ASSIGN; // case(12): return WORK_STATUS; case(13): return WORK_COMPLETE; case(14): return WORK_FAIL; // case(15): return GET_STATUS; case(16): return ECHO_REQ; case(17): return ECHO_RES; // case(18): return SUBMIT_JOB_BG; case(19): return ERROR; case(20): return STATUS_RES; // case(21): return SUBMIT_JOB_HIGH; case(22): return SET_CLIENT_ID; case(23): return CAN_DO_TIMEOUT; // case(24): return ALL_YOURS; case(25): return WORK_EXCEPTION; case(26): return OPTION_REQ; // case(27): return OPTION_RES; case(28): return WORK_DATA; case(29): return WORK_WARNING; // case(30): return GRAB_JOB_UNIQ; case(31): return JOB_ASSIGN_UNIQ; case(32): return SUBMIT_JOB_HIGH_BG; // case(33): return SUBMIT_JOB_LOW; case(34): return SUBMIT_JOB_LOW_BG;case(35): return SUBMIT_JOB_SCHED; // case(36): return SUBMIT_JOB_EPOCH; // default: // return null; // } // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.gearman.core.GearmanPacket.Magic; import org.gearman.core.GearmanPacket.Type;
return packet.toBytes(); } @Override public final void init(final GearmanCodecChannel<Integer> channel) { channel.setCodecAttachement(FORMAT); } private final void format(final GearmanCodecChannel<Integer> channel) { final ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; if(buffer.get(0)==0) { buffer.limit(HEADER_SIZE); channel.setCodecAttachement(HEADER); } else { channel.setCodecAttachement(TEXT); text(channel); } } private final void header(final GearmanCodecChannel<Integer> channel) { ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; final int size = buffer.getInt(SIZE_POS); if(size==0) { buffer.flip();
// Path: src/org/gearman/core/GearmanPacket.java // public static enum Magic { // /** // * A request packet is sent to the server to request a service.<br> // * Magic code = "\0REQ" = 5391697 // */ // REQ(5391697), // // /** // * A response packet is sent from the server to a client or worker as a response // * from handling a request.<br> // * Magic code = "\0RES" = 5391699 // */ // RES(5391699); // // /** The magic number */ // private final int code; // // private Magic(int code) { // this.code = code; // } // // /** // * Returns the magic code // * @return // * The magic code. // */ // public final int getMagicCode() { // return code; // } // // /** // * Gets the <code>Magic</code> enumerator based on the magic code // * @param code // * The magic code. // * @return // * The Magic object. If the code is invalid, null is returned // */ // public static final Magic fromMagicCode(final int code) { // switch(code) { // case 5391697: // return REQ; // case 5391699: // return RES; // default: // return null; // } // } // } // // Path: src/org/gearman/core/GearmanPacket.java // public static enum Type{ // TEXT(0,1), CAN_DO(1,1), CANT_DO(2,1), RESET_ABILITIES(3,0), PRE_SLEEP(4,0), UNUSED(5,0), // NOOP(6,0), SUBMIT_JOB(7,3), JOB_CREATED(8,1), GRAB_JOB(9,0), NO_JOB(10,0), JOB_ASSIGN(11,3), // WORK_STATUS(12, 3), WORK_COMPLETE(13,2), WORK_FAIL(14,1), GET_STATUS(15,1), ECHO_REQ(16,1), // ECHO_RES(17,1), SUBMIT_JOB_BG(18,3), ERROR(19, 2), STATUS_RES(20, 5), SUBMIT_JOB_HIGH(21,3), // SET_CLIENT_ID(22,1), CAN_DO_TIMEOUT(23,2), ALL_YOURS(24,0), WORK_EXCEPTION(25,2), // OPTION_REQ(26,1), OPTION_RES(27,1), WORK_DATA(28,2), WORK_WARNING(29, 2), GRAB_JOB_UNIQ(30,0), // JOB_ASSIGN_UNIQ(31,4), SUBMIT_JOB_HIGH_BG(32,3), SUBMIT_JOB_LOW(33,3), SUBMIT_JOB_LOW_BG(34,3), // SUBMIT_JOB_SCHED(35,8), SUBMIT_JOB_EPOCH(36,4); // // private final int type; // private final int args; // private Type(final int type, final int args) { // this.type = type; // this.args = args; // } // // public final int getTypeValue() { // return type; // } // public final int getArgumentCount() { // return args; // } // // public static final Type fromTypeValue(final int value) { // switch(value) { // case(0): return TEXT; case(1): return CAN_DO; case(2): return CANT_DO; // case(3): return RESET_ABILITIES; case(4): return PRE_SLEEP; case(5): return UNUSED; // case(6): return NOOP; case(7): return SUBMIT_JOB; case(8): return JOB_CREATED; // case(9): return GRAB_JOB; case(10): return NO_JOB; case(11): return JOB_ASSIGN; // case(12): return WORK_STATUS; case(13): return WORK_COMPLETE; case(14): return WORK_FAIL; // case(15): return GET_STATUS; case(16): return ECHO_REQ; case(17): return ECHO_RES; // case(18): return SUBMIT_JOB_BG; case(19): return ERROR; case(20): return STATUS_RES; // case(21): return SUBMIT_JOB_HIGH; case(22): return SET_CLIENT_ID; case(23): return CAN_DO_TIMEOUT; // case(24): return ALL_YOURS; case(25): return WORK_EXCEPTION; case(26): return OPTION_REQ; // case(27): return OPTION_RES; case(28): return WORK_DATA; case(29): return WORK_WARNING; // case(30): return GRAB_JOB_UNIQ; case(31): return JOB_ASSIGN_UNIQ; case(32): return SUBMIT_JOB_HIGH_BG; // case(33): return SUBMIT_JOB_LOW; case(34): return SUBMIT_JOB_LOW_BG;case(35): return SUBMIT_JOB_SCHED; // case(36): return SUBMIT_JOB_EPOCH; // default: // return null; // } // } // } // Path: src/org/gearman/core/StandardCodec.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.gearman.core.GearmanPacket.Magic; import org.gearman.core.GearmanPacket.Type; return packet.toBytes(); } @Override public final void init(final GearmanCodecChannel<Integer> channel) { channel.setCodecAttachement(FORMAT); } private final void format(final GearmanCodecChannel<Integer> channel) { final ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; if(buffer.get(0)==0) { buffer.limit(HEADER_SIZE); channel.setCodecAttachement(HEADER); } else { channel.setCodecAttachement(TEXT); text(channel); } } private final void header(final GearmanCodecChannel<Integer> channel) { ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; final int size = buffer.getInt(SIZE_POS); if(size==0) { buffer.flip();
final Magic magic = Magic.fromMagicCode(buffer.getInt());
fwix/java-gearman
src/org/gearman/core/StandardCodec.java
// Path: src/org/gearman/core/GearmanPacket.java // public static enum Magic { // /** // * A request packet is sent to the server to request a service.<br> // * Magic code = "\0REQ" = 5391697 // */ // REQ(5391697), // // /** // * A response packet is sent from the server to a client or worker as a response // * from handling a request.<br> // * Magic code = "\0RES" = 5391699 // */ // RES(5391699); // // /** The magic number */ // private final int code; // // private Magic(int code) { // this.code = code; // } // // /** // * Returns the magic code // * @return // * The magic code. // */ // public final int getMagicCode() { // return code; // } // // /** // * Gets the <code>Magic</code> enumerator based on the magic code // * @param code // * The magic code. // * @return // * The Magic object. If the code is invalid, null is returned // */ // public static final Magic fromMagicCode(final int code) { // switch(code) { // case 5391697: // return REQ; // case 5391699: // return RES; // default: // return null; // } // } // } // // Path: src/org/gearman/core/GearmanPacket.java // public static enum Type{ // TEXT(0,1), CAN_DO(1,1), CANT_DO(2,1), RESET_ABILITIES(3,0), PRE_SLEEP(4,0), UNUSED(5,0), // NOOP(6,0), SUBMIT_JOB(7,3), JOB_CREATED(8,1), GRAB_JOB(9,0), NO_JOB(10,0), JOB_ASSIGN(11,3), // WORK_STATUS(12, 3), WORK_COMPLETE(13,2), WORK_FAIL(14,1), GET_STATUS(15,1), ECHO_REQ(16,1), // ECHO_RES(17,1), SUBMIT_JOB_BG(18,3), ERROR(19, 2), STATUS_RES(20, 5), SUBMIT_JOB_HIGH(21,3), // SET_CLIENT_ID(22,1), CAN_DO_TIMEOUT(23,2), ALL_YOURS(24,0), WORK_EXCEPTION(25,2), // OPTION_REQ(26,1), OPTION_RES(27,1), WORK_DATA(28,2), WORK_WARNING(29, 2), GRAB_JOB_UNIQ(30,0), // JOB_ASSIGN_UNIQ(31,4), SUBMIT_JOB_HIGH_BG(32,3), SUBMIT_JOB_LOW(33,3), SUBMIT_JOB_LOW_BG(34,3), // SUBMIT_JOB_SCHED(35,8), SUBMIT_JOB_EPOCH(36,4); // // private final int type; // private final int args; // private Type(final int type, final int args) { // this.type = type; // this.args = args; // } // // public final int getTypeValue() { // return type; // } // public final int getArgumentCount() { // return args; // } // // public static final Type fromTypeValue(final int value) { // switch(value) { // case(0): return TEXT; case(1): return CAN_DO; case(2): return CANT_DO; // case(3): return RESET_ABILITIES; case(4): return PRE_SLEEP; case(5): return UNUSED; // case(6): return NOOP; case(7): return SUBMIT_JOB; case(8): return JOB_CREATED; // case(9): return GRAB_JOB; case(10): return NO_JOB; case(11): return JOB_ASSIGN; // case(12): return WORK_STATUS; case(13): return WORK_COMPLETE; case(14): return WORK_FAIL; // case(15): return GET_STATUS; case(16): return ECHO_REQ; case(17): return ECHO_RES; // case(18): return SUBMIT_JOB_BG; case(19): return ERROR; case(20): return STATUS_RES; // case(21): return SUBMIT_JOB_HIGH; case(22): return SET_CLIENT_ID; case(23): return CAN_DO_TIMEOUT; // case(24): return ALL_YOURS; case(25): return WORK_EXCEPTION; case(26): return OPTION_REQ; // case(27): return OPTION_RES; case(28): return WORK_DATA; case(29): return WORK_WARNING; // case(30): return GRAB_JOB_UNIQ; case(31): return JOB_ASSIGN_UNIQ; case(32): return SUBMIT_JOB_HIGH_BG; // case(33): return SUBMIT_JOB_LOW; case(34): return SUBMIT_JOB_LOW_BG;case(35): return SUBMIT_JOB_SCHED; // case(36): return SUBMIT_JOB_EPOCH; // default: // return null; // } // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.gearman.core.GearmanPacket.Magic; import org.gearman.core.GearmanPacket.Type;
} @Override public final void init(final GearmanCodecChannel<Integer> channel) { channel.setCodecAttachement(FORMAT); } private final void format(final GearmanCodecChannel<Integer> channel) { final ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; if(buffer.get(0)==0) { buffer.limit(HEADER_SIZE); channel.setCodecAttachement(HEADER); } else { channel.setCodecAttachement(TEXT); text(channel); } } private final void header(final GearmanCodecChannel<Integer> channel) { ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; final int size = buffer.getInt(SIZE_POS); if(size==0) { buffer.flip(); final Magic magic = Magic.fromMagicCode(buffer.getInt());
// Path: src/org/gearman/core/GearmanPacket.java // public static enum Magic { // /** // * A request packet is sent to the server to request a service.<br> // * Magic code = "\0REQ" = 5391697 // */ // REQ(5391697), // // /** // * A response packet is sent from the server to a client or worker as a response // * from handling a request.<br> // * Magic code = "\0RES" = 5391699 // */ // RES(5391699); // // /** The magic number */ // private final int code; // // private Magic(int code) { // this.code = code; // } // // /** // * Returns the magic code // * @return // * The magic code. // */ // public final int getMagicCode() { // return code; // } // // /** // * Gets the <code>Magic</code> enumerator based on the magic code // * @param code // * The magic code. // * @return // * The Magic object. If the code is invalid, null is returned // */ // public static final Magic fromMagicCode(final int code) { // switch(code) { // case 5391697: // return REQ; // case 5391699: // return RES; // default: // return null; // } // } // } // // Path: src/org/gearman/core/GearmanPacket.java // public static enum Type{ // TEXT(0,1), CAN_DO(1,1), CANT_DO(2,1), RESET_ABILITIES(3,0), PRE_SLEEP(4,0), UNUSED(5,0), // NOOP(6,0), SUBMIT_JOB(7,3), JOB_CREATED(8,1), GRAB_JOB(9,0), NO_JOB(10,0), JOB_ASSIGN(11,3), // WORK_STATUS(12, 3), WORK_COMPLETE(13,2), WORK_FAIL(14,1), GET_STATUS(15,1), ECHO_REQ(16,1), // ECHO_RES(17,1), SUBMIT_JOB_BG(18,3), ERROR(19, 2), STATUS_RES(20, 5), SUBMIT_JOB_HIGH(21,3), // SET_CLIENT_ID(22,1), CAN_DO_TIMEOUT(23,2), ALL_YOURS(24,0), WORK_EXCEPTION(25,2), // OPTION_REQ(26,1), OPTION_RES(27,1), WORK_DATA(28,2), WORK_WARNING(29, 2), GRAB_JOB_UNIQ(30,0), // JOB_ASSIGN_UNIQ(31,4), SUBMIT_JOB_HIGH_BG(32,3), SUBMIT_JOB_LOW(33,3), SUBMIT_JOB_LOW_BG(34,3), // SUBMIT_JOB_SCHED(35,8), SUBMIT_JOB_EPOCH(36,4); // // private final int type; // private final int args; // private Type(final int type, final int args) { // this.type = type; // this.args = args; // } // // public final int getTypeValue() { // return type; // } // public final int getArgumentCount() { // return args; // } // // public static final Type fromTypeValue(final int value) { // switch(value) { // case(0): return TEXT; case(1): return CAN_DO; case(2): return CANT_DO; // case(3): return RESET_ABILITIES; case(4): return PRE_SLEEP; case(5): return UNUSED; // case(6): return NOOP; case(7): return SUBMIT_JOB; case(8): return JOB_CREATED; // case(9): return GRAB_JOB; case(10): return NO_JOB; case(11): return JOB_ASSIGN; // case(12): return WORK_STATUS; case(13): return WORK_COMPLETE; case(14): return WORK_FAIL; // case(15): return GET_STATUS; case(16): return ECHO_REQ; case(17): return ECHO_RES; // case(18): return SUBMIT_JOB_BG; case(19): return ERROR; case(20): return STATUS_RES; // case(21): return SUBMIT_JOB_HIGH; case(22): return SET_CLIENT_ID; case(23): return CAN_DO_TIMEOUT; // case(24): return ALL_YOURS; case(25): return WORK_EXCEPTION; case(26): return OPTION_REQ; // case(27): return OPTION_RES; case(28): return WORK_DATA; case(29): return WORK_WARNING; // case(30): return GRAB_JOB_UNIQ; case(31): return JOB_ASSIGN_UNIQ; case(32): return SUBMIT_JOB_HIGH_BG; // case(33): return SUBMIT_JOB_LOW; case(34): return SUBMIT_JOB_LOW_BG;case(35): return SUBMIT_JOB_SCHED; // case(36): return SUBMIT_JOB_EPOCH; // default: // return null; // } // } // } // Path: src/org/gearman/core/StandardCodec.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.gearman.core.GearmanPacket.Magic; import org.gearman.core.GearmanPacket.Type; } @Override public final void init(final GearmanCodecChannel<Integer> channel) { channel.setCodecAttachement(FORMAT); } private final void format(final GearmanCodecChannel<Integer> channel) { final ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; if(buffer.get(0)==0) { buffer.limit(HEADER_SIZE); channel.setCodecAttachement(HEADER); } else { channel.setCodecAttachement(TEXT); text(channel); } } private final void header(final GearmanCodecChannel<Integer> channel) { ByteBuffer buffer = channel.getBuffer(); if(buffer.hasRemaining()) return; final int size = buffer.getInt(SIZE_POS); if(size==0) { buffer.flip(); final Magic magic = Magic.fromMagicCode(buffer.getInt());
final Type type = Type.fromTypeValue(buffer.getInt());
fwix/java-gearman
src/org/gearman/GMServerFunctionMap.java
// Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // // Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // };
import org.gearman.util.ByteArray; import org.gearman.ServerJob.JobPriority;
package org.gearman; public class GMServerFunctionMap { public static final String GM_TASK = "gm_task";
// Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // // Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // Path: src/org/gearman/GMServerFunctionMap.java import org.gearman.util.ByteArray; import org.gearman.ServerJob.JobPriority; package org.gearman; public class GMServerFunctionMap { public static final String GM_TASK = "gm_task";
public static final ByteArray GM_TASK_BA = new ByteArray(GM_TASK.getBytes());
fwix/java-gearman
src/org/gearman/GMServerFunctionMap.java
// Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // // Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // };
import org.gearman.util.ByteArray; import org.gearman.ServerJob.JobPriority;
package org.gearman; public class GMServerFunctionMap { public static final String GM_TASK = "gm_task"; public static final ByteArray GM_TASK_BA = new ByteArray(GM_TASK.getBytes()); public final ServerFunction getFunction(ServerFunctionMap map, ByteArray name){ if (name.toString().equals(GM_TASK)){ return new GMServerFunction(); } return map.getFunction(name); } class GMServerFunction implements ServerFunction{ public void removeJobs(){ } public void wakeUp(){ } public Integer getWorkingCount(){ return null; } public void addNoopable(final ServerClient noopable) { // DO NOTHING } public void removeNoopable(final ServerClient noopable){ // DO NOTHING } public void setMaxQueue(final int size){ //DO NOTHING } public ByteArray getName(){ return GM_TASK_BA; } public boolean queueIsEmpty(){ return GMServerFunctionMap.this.isQueueEmpty(); }
// Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // // Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // Path: src/org/gearman/GMServerFunctionMap.java import org.gearman.util.ByteArray; import org.gearman.ServerJob.JobPriority; package org.gearman; public class GMServerFunctionMap { public static final String GM_TASK = "gm_task"; public static final ByteArray GM_TASK_BA = new ByteArray(GM_TASK.getBytes()); public final ServerFunction getFunction(ServerFunctionMap map, ByteArray name){ if (name.toString().equals(GM_TASK)){ return new GMServerFunction(); } return map.getFunction(name); } class GMServerFunction implements ServerFunction{ public void removeJobs(){ } public void wakeUp(){ } public Integer getWorkingCount(){ return null; } public void addNoopable(final ServerClient noopable) { // DO NOTHING } public void removeNoopable(final ServerClient noopable){ // DO NOTHING } public void setMaxQueue(final int size){ //DO NOTHING } public ByteArray getName(){ return GM_TASK_BA; } public boolean queueIsEmpty(){ return GMServerFunctionMap.this.isQueueEmpty(); }
public void createJob(final ByteArray uniqueID, final byte[] data, final JobPriority priority, final ServerClient creator, boolean isBackground){
fwix/java-gearman
src/org/gearman/GearmanClient.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // }
import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult;
package org.gearman; /** * A GearmanCliet submits {@link GearmanJob}s and {@link GearmanBackgroundJob}s * to gearman job servers * * @author isaiah.v */ public interface GearmanClient extends GearmanJobServerPool { /** * * @author isaiah * */ public static enum SubmitCallbackResult implements GearmanCallbackResult{ /** * The job was sucessfuly submitted to a job server */ SUBMIT_SUCCESSFUL, /** * Failed to send the job due to there being no job servers to * submit to. */ FAILED_TO_NO_SERVER, /** * */ FAILED_TO_CONNECT, /** * The job has already been submitted to a client and has not yet completed */ FAILED_TO_INVALID_JOB_STATE, /** * The {@link GearmanClient} is shutdown */ FAILED_TO_SHUTDOWN; @Override public boolean isSuccessful() { return this==SUBMIT_SUCCESSFUL; } }
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // Path: src/org/gearman/GearmanClient.java import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanCallbackResult; package org.gearman; /** * A GearmanCliet submits {@link GearmanJob}s and {@link GearmanBackgroundJob}s * to gearman job servers * * @author isaiah.v */ public interface GearmanClient extends GearmanJobServerPool { /** * * @author isaiah * */ public static enum SubmitCallbackResult implements GearmanCallbackResult{ /** * The job was sucessfuly submitted to a job server */ SUBMIT_SUCCESSFUL, /** * Failed to send the job due to there being no job servers to * submit to. */ FAILED_TO_NO_SERVER, /** * */ FAILED_TO_CONNECT, /** * The job has already been submitted to a client and has not yet completed */ FAILED_TO_INVALID_JOB_STATE, /** * The {@link GearmanClient} is shutdown */ FAILED_TO_SHUTDOWN; @Override public boolean isSuccessful() { return this==SUBMIT_SUCCESSFUL; } }
public interface GearmanSubmitHandler extends GearmanCallbackHandler<GearmanJob, SubmitCallbackResult>{}
fwix/java-gearman
src/org/gearman/ServerFunction.java
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // }
import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray;
package org.gearman; public interface ServerFunction { public void addNoopable(final ServerClient noopable) ; public void removeNoopable(final ServerClient noopable); public void setMaxQueue(final int size);
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // Path: src/org/gearman/ServerFunction.java import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray; package org.gearman; public interface ServerFunction { public void addNoopable(final ServerClient noopable) ; public void removeNoopable(final ServerClient noopable); public void setMaxQueue(final int size);
public ByteArray getName() ;
fwix/java-gearman
src/org/gearman/ServerFunction.java
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // }
import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray;
package org.gearman; public interface ServerFunction { public void addNoopable(final ServerClient noopable) ; public void removeNoopable(final ServerClient noopable); public void setMaxQueue(final int size); public ByteArray getName() ; public boolean queueIsEmpty();
// Path: src/org/gearman/ServerJob.java // public static enum JobPriority { // LOW, MID, HIGH // }; // // Path: src/org/gearman/util/ByteArray.java // public final class ByteArray { // private final byte[] array; // // public ByteArray(final byte[] array) { // this.array = array; // } // // @Override // public final int hashCode() { // return Arrays.hashCode(array); // } // // public final byte[] getBytes() { // return array.clone(); // } // // public final String toString(Charset charset) { // return new String(array, charset); // } // // @Override // public final String toString() { // return new String(array); // } // // @Override // public final boolean equals(final Object obj) { // if(obj instanceof ByteArray) // return this.equals((ByteArray)obj); // else if(obj instanceof byte[]) // return this.equals((byte[])obj); // else // return false; // } // // public final boolean equals(final ByteArray array) { // return this == array || this.equals(array.array); // } // // public final boolean equals(final byte[] array) { // return Arrays.equals(this.array, array); // } // } // Path: src/org/gearman/ServerFunction.java import org.gearman.ServerJob.JobPriority; import org.gearman.util.ByteArray; package org.gearman; public interface ServerFunction { public void addNoopable(final ServerClient noopable) ; public void removeNoopable(final ServerClient noopable); public void setMaxQueue(final int size); public ByteArray getName() ; public boolean queueIsEmpty();
public void createJob(final ByteArray uniqueID, final byte[] data, final JobPriority priority, final ServerClient creator, boolean isBackground);
fwix/java-gearman
src/org/gearman/ClientImpl.java
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // }
import java.net.InetSocketAddress; import java.util.Deque; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; import org.gearman.core.GearmanCallbackResult;
package org.gearman; class ClientImpl extends JobServerPoolAbstract<ClientImpl.InnerConnectionController<?,?>> implements GearmanClient { protected class InnerConnectionController<K, C extends GearmanCallbackResult> extends ClientConnectionController<K,C> { InnerConnectionController(K key) { super(ClientImpl.this, key); } @Override protected Gearman getGearman() { return ClientImpl.this.gearman; } @Override protected ClientJobSubmission pollNextJob() { return ClientImpl.this.pollJob(); } @Override protected void requeueJob(ClientJobSubmission jobSub) { /* * Note: this method may me called by super.close() */ ClientImpl.this.requeueJob(jobSub); } @Override protected void onConnect(ControllerState oldState) { } @Override
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // Path: src/org/gearman/ClientImpl.java import java.net.InetSocketAddress; import java.util.Deque; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; import org.gearman.core.GearmanCallbackResult; package org.gearman; class ClientImpl extends JobServerPoolAbstract<ClientImpl.InnerConnectionController<?,?>> implements GearmanClient { protected class InnerConnectionController<K, C extends GearmanCallbackResult> extends ClientConnectionController<K,C> { InnerConnectionController(K key) { super(ClientImpl.this, key); } @Override protected Gearman getGearman() { return ClientImpl.this.gearman; } @Override protected ClientJobSubmission pollNextJob() { return ClientImpl.this.pollJob(); } @Override protected void requeueJob(ClientJobSubmission jobSub) { /* * Note: this method may me called by super.close() */ ClientImpl.this.requeueJob(jobSub); } @Override protected void onConnect(ControllerState oldState) { } @Override
protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) {
fwix/java-gearman
src/org/gearman/ClientImpl.java
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // }
import java.net.InetSocketAddress; import java.util.Deque; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; import org.gearman.core.GearmanCallbackResult;
*/ // notify the user of the connection being dropped policy.lostLocalServer(this.getKey(), ClientImpl.this, grounds); // remove "this" from the client super.dropServer(); } @Override protected void onConnect(ControllerState oldState) { super.onConnect(oldState); /* * Open a new local connection. This connection controller is both * the GearmanConnectionHandler and GearmanFailureHandler */ super.getKey().createGearmanConnection(this, this); } } private final class RemoteConnectionController extends InnerConnectionController<InetSocketAddress, org.gearman.core.GearmanConnectionManager.ConnectCallbackResult> implements Runnable{ RemoteConnectionController(InetSocketAddress key) { super(key); } @Override protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) { super.onLostConnection(policy, grounds);
// Path: src/org/gearman/GearmanLostConnectionPolicy.java // public final static class Action { // // static final Action RECONNECT = new Action(0); // static final Action DROP = new Action(0); // // private final long nanoTime; // // private Action(final long nanoTime) { // this.nanoTime = nanoTime; // } // // /** // * Tells the calling service to reconnect at it's own discretion // */ // public static Action reconnectServer() { // return RECONNECT; // } // // /** // * Tells the calling service to reconnect no earlier then the the specified delay // * // * @param time // * The amount of time that must pass before any attempts to reconnect can occur // * @param unit // * The unit time // */ // public static Action reconnectServer(long time, final TimeUnit unit) { // if(time<0) time=0; // return new Action(unit.toNanos(time)); // } // // /** // * Tells the calling service to drop the server from its control // */ // public static Action dropServer() { // return DROP; // } // // /** // * Returns the amount of time the gearman service must wait before attempting // * to reconnect // * // * @return // * The amount of time the gearman service must wait before attempting // * to reconnect // */ // long getNanoTime() { // return nanoTime; // } // } // // Path: src/org/gearman/GearmanLostConnectionPolicy.java // public static enum Grounds { // // /** // * The server in question unexpectedly disconnected. // */ // UNEXPECTED_DISCONNECT, // // /** // * The gearman service failed to connect to a server registed with the service // */ // FAILED_CONNECTION, // // /** // * The connection was closed due to a server failing to respond // */ // RESPONCE_TIMEOUT, // }; // // Path: src/org/gearman/core/GearmanCallbackResult.java // public interface GearmanCallbackResult { // // /** // * Tests if the operation completed successfully // * @return // * <code>true</code> if and only if the operation was successful // */ // public boolean isSuccessful(); // } // Path: src/org/gearman/ClientImpl.java import java.net.InetSocketAddress; import java.util.Deque; import java.util.Queue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.gearman.GearmanLostConnectionPolicy.Action; import org.gearman.GearmanLostConnectionPolicy.Grounds; import org.gearman.core.GearmanCallbackResult; */ // notify the user of the connection being dropped policy.lostLocalServer(this.getKey(), ClientImpl.this, grounds); // remove "this" from the client super.dropServer(); } @Override protected void onConnect(ControllerState oldState) { super.onConnect(oldState); /* * Open a new local connection. This connection controller is both * the GearmanConnectionHandler and GearmanFailureHandler */ super.getKey().createGearmanConnection(this, this); } } private final class RemoteConnectionController extends InnerConnectionController<InetSocketAddress, org.gearman.core.GearmanConnectionManager.ConnectCallbackResult> implements Runnable{ RemoteConnectionController(InetSocketAddress key) { super(key); } @Override protected void onLostConnection(GearmanLostConnectionPolicy policy, Grounds grounds) { super.onLostConnection(policy, grounds);
Action action = null;
fwix/java-gearman
src/org/gearman/JobStatus.java
// Path: src/org/gearman/GearmanJobStatus.java // public interface StatusResult extends GearmanCallbackResult { // public GearmanJobStatus getGearmanJobStatus(); // public StatusCallbackResult getStatusCallbackResult(); // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // }
import org.gearman.GearmanJobStatus.StatusResult; import org.gearman.core.GearmanCallbackHandler;
package org.gearman; class JobStatus implements GearmanJobStatus, StatusResult { public static final long OP_TIMEOUT = 20000; private StatusCallbackResult result;
// Path: src/org/gearman/GearmanJobStatus.java // public interface StatusResult extends GearmanCallbackResult { // public GearmanJobStatus getGearmanJobStatus(); // public StatusCallbackResult getStatusCallbackResult(); // } // // Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // Path: src/org/gearman/JobStatus.java import org.gearman.GearmanJobStatus.StatusResult; import org.gearman.core.GearmanCallbackHandler; package org.gearman; class JobStatus implements GearmanJobStatus, StatusResult { public static final long OP_TIMEOUT = 20000; private StatusCallbackResult result;
private GearmanCallbackHandler<GearmanJob, StatusResult> callback;
fwix/java-gearman
src/org/gearman/reactor/NioReactor.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanConnectionManager.java // public enum ConnectCallbackResult implements GearmanCallbackResult { // SUCCESS, // SERVICE_SHUTDOWN, // CONNECTION_FAILED; // // @Override // public boolean isSuccessful() { // return this.equals(SUCCESS); // } // }
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AcceptPendingException; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.channels.NotYetBoundException; import java.nio.channels.ShutdownChannelGroupException; import java.util.Collections; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanConnectionManager.ConnectCallbackResult;
public boolean isShutdown() { return asyncChannelGroup.isShutdown(); } public synchronized boolean closePort(int port) throws IOException { final AsynchronousServerSocketChannel server = this.ports.remove(port); if(server==null) return false; server.close(); return true; } public synchronized void closePorts() { Iterator<AsynchronousServerSocketChannel> it = this.ports.values().iterator(); while(it.hasNext()) { try { AsynchronousServerSocketChannel assc = it.next(); assc.close(); it.remove(); } catch (IOException e) { // TODO log error } } } public synchronized Set<Integer> getOpenPorts() { return Collections.unmodifiableSet(this.ports.keySet()); }
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanConnectionManager.java // public enum ConnectCallbackResult implements GearmanCallbackResult { // SUCCESS, // SERVICE_SHUTDOWN, // CONNECTION_FAILED; // // @Override // public boolean isSuccessful() { // return this.equals(SUCCESS); // } // } // Path: src/org/gearman/reactor/NioReactor.java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AcceptPendingException; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.channels.NotYetBoundException; import java.nio.channels.ShutdownChannelGroupException; import java.util.Collections; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanConnectionManager.ConnectCallbackResult; public boolean isShutdown() { return asyncChannelGroup.isShutdown(); } public synchronized boolean closePort(int port) throws IOException { final AsynchronousServerSocketChannel server = this.ports.remove(port); if(server==null) return false; server.close(); return true; } public synchronized void closePorts() { Iterator<AsynchronousServerSocketChannel> it = this.ports.values().iterator(); while(it.hasNext()) { try { AsynchronousServerSocketChannel assc = it.next(); assc.close(); it.remove(); } catch (IOException e) { // TODO log error } } } public synchronized Set<Integer> getOpenPorts() { return Collections.unmodifiableSet(this.ports.keySet()); }
public final <X> void openSocket(final InetSocketAddress adrs, final SocketHandler<X> sHandler, final GearmanCallbackHandler<InetSocketAddress, ConnectCallbackResult> callback) {
fwix/java-gearman
src/org/gearman/reactor/NioReactor.java
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanConnectionManager.java // public enum ConnectCallbackResult implements GearmanCallbackResult { // SUCCESS, // SERVICE_SHUTDOWN, // CONNECTION_FAILED; // // @Override // public boolean isSuccessful() { // return this.equals(SUCCESS); // } // }
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AcceptPendingException; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.channels.NotYetBoundException; import java.nio.channels.ShutdownChannelGroupException; import java.util.Collections; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanConnectionManager.ConnectCallbackResult;
public boolean isShutdown() { return asyncChannelGroup.isShutdown(); } public synchronized boolean closePort(int port) throws IOException { final AsynchronousServerSocketChannel server = this.ports.remove(port); if(server==null) return false; server.close(); return true; } public synchronized void closePorts() { Iterator<AsynchronousServerSocketChannel> it = this.ports.values().iterator(); while(it.hasNext()) { try { AsynchronousServerSocketChannel assc = it.next(); assc.close(); it.remove(); } catch (IOException e) { // TODO log error } } } public synchronized Set<Integer> getOpenPorts() { return Collections.unmodifiableSet(this.ports.keySet()); }
// Path: src/org/gearman/core/GearmanCallbackHandler.java // public interface GearmanCallbackHandler<D,R extends GearmanCallbackResult> { // public void onComplete(D data, R result); // } // // Path: src/org/gearman/core/GearmanConnectionManager.java // public enum ConnectCallbackResult implements GearmanCallbackResult { // SUCCESS, // SERVICE_SHUTDOWN, // CONNECTION_FAILED; // // @Override // public boolean isSuccessful() { // return this.equals(SUCCESS); // } // } // Path: src/org/gearman/reactor/NioReactor.java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AcceptPendingException; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.channels.NotYetBoundException; import java.nio.channels.ShutdownChannelGroupException; import java.util.Collections; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import org.gearman.core.GearmanCallbackHandler; import org.gearman.core.GearmanConnectionManager.ConnectCallbackResult; public boolean isShutdown() { return asyncChannelGroup.isShutdown(); } public synchronized boolean closePort(int port) throws IOException { final AsynchronousServerSocketChannel server = this.ports.remove(port); if(server==null) return false; server.close(); return true; } public synchronized void closePorts() { Iterator<AsynchronousServerSocketChannel> it = this.ports.values().iterator(); while(it.hasNext()) { try { AsynchronousServerSocketChannel assc = it.next(); assc.close(); it.remove(); } catch (IOException e) { // TODO log error } } } public synchronized Set<Integer> getOpenPorts() { return Collections.unmodifiableSet(this.ports.keySet()); }
public final <X> void openSocket(final InetSocketAddress adrs, final SocketHandler<X> sHandler, final GearmanCallbackHandler<InetSocketAddress, ConnectCallbackResult> callback) {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
return null; } return val; } public String getProperty(String key, String def) { String val = getProperty(key); if (val == null) { val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); }
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; return null; } return val; } public String getProperty(String key, String def) { String val = getProperty(key); if (val == null) { val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); }
public Class<? extends ProxyFactory> getProxyFactoryClass() {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
public String getProperty(String key, String def) { String val = getProperty(key); if (val == null) { val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect":
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; public String getProperty(String key, String def) { String val = getProperty(key); if (val == null) { val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect":
factoryClass = ReflectProxyFactory.class;
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect": factoryClass = ReflectProxyFactory.class; break; case "cglib":
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; val = def; } return val; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect": factoryClass = ReflectProxyFactory.class; break; case "cglib":
factoryClass = CGLibProxyFactory.class;
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
} private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect": factoryClass = ReflectProxyFactory.class; break; case "cglib": factoryClass = CGLibProxyFactory.class; break; case "caching":
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/CachingProxyFactory.java // public class CachingProxyFactory implements ProxyFactory { // private final ConcurrentHashMap<ProxyClass, Constructor<?>> constructorCache = new ConcurrentHashMap<>(); // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // Constructor constructor = constructorCache.get(proxyClass); // if (constructor == null) { // constructor = proxyClass.createConstructor(); // final Constructor oldConstructor = constructorCache.putIfAbsent(proxyClass, constructor); // constructor = oldConstructor == null ? constructor : oldConstructor; // } // try { // return (T) constructor.newInstance(proxyHandler); // } catch (ReflectiveOperationException reflectiveOperationException) { // throw new ProxyException(reflectiveOperationException); // } // } // /** // * Clears the constructor cache // */ // public void clearCache() { // constructorCache.clear(); // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/DriverUrl.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.CachingProxyFactory; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; } private static <T> Class<T> toClass(String className) { if (className == null) { return null; } try { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return clazz; } catch (ClassNotFoundException classNotFoundException) { throw new IllegalArgumentException("Property " + className + " is not a valid class", classNotFoundException); } } public Class<? extends Driver> getDriverClass() { return toClass(getProperty("metrics_driver")); } public Class<? extends ProxyFactory> getProxyFactoryClass() { Class<? extends ProxyFactory> factoryClass; String proxyFactoryName = getProperty("metrics_proxy_factory", "reflect"); switch (proxyFactoryName) { case "reflect": factoryClass = ReflectProxyFactory.class; break; case "cglib": factoryClass = CGLibProxyFactory.class; break; case "caching":
factoryClass = CachingProxyFactory.class;
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/ResultSetProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.ResultSet; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC proxy handler for {@link ResultSet} and its subclasses. * * @param <T> Proxied ResultSet type */ public class ResultSetProxyHandler<T extends ResultSet> extends JdbcProxyHandler<T> { private final Query query; public ResultSetProxyHandler(T delegate, Class<T> delegateType, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, delegateType, proxyFactory, lifeTimerContext); this.query = query; } private static final InvocationFilter THIS_INVOCATION_FILTER = new MethodNamesInvocationFilter("isWrapperFor", "unwrap", "close"); @Override
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/ResultSetProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.ResultSet; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC proxy handler for {@link ResultSet} and its subclasses. * * @param <T> Proxied ResultSet type */ public class ResultSetProxyHandler<T extends ResultSet> extends JdbcProxyHandler<T> { private final Query query; public ResultSetProxyHandler(T delegate, Class<T> delegateType, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, delegateType, proxyFactory, lifeTimerContext); this.query = query; } private static final InvocationFilter THIS_INVOCATION_FILTER = new MethodNamesInvocationFilter("isWrapperFor", "unwrap", "close"); @Override
protected Object invoke(MethodInvocation<T> delegatingMethodInvocation) throws Throwable {
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/MeteringTest.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import javax.sql.DataSource; import java.sql.*; import java.util.Random; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Slf4jReporter; import com.codahale.metrics.Snapshot; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metering test */ public class MeteringTest { private static final Logger LOGGER = LoggerFactory.getLogger(MeteringTest.class); private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; private DataSource rawDataSource; private DataSource dataSource; private Slf4jReporter metricsReporter; @Before public void setUp() throws SQLException { metricRegistry = new MetricRegistry(); metricsReporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LOGGER) .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) .build(); rawDataSource = H2DbUtil.createDataSource(); try (Connection connection = rawDataSource.getConnection()) { H2DbUtil.initTable(connection); } proxyFactory = MetricsSql.forRegistry(metricRegistry)
// Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/test/java/com/github/gquintana/metrics/sql/MeteringTest.java import javax.sql.DataSource; import java.sql.*; import java.util.Random; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Slf4jReporter; import com.codahale.metrics.Snapshot; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metering test */ public class MeteringTest { private static final Logger LOGGER = LoggerFactory.getLogger(MeteringTest.class); private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; private DataSource rawDataSource; private DataSource dataSource; private Slf4jReporter metricsReporter; @Before public void setUp() throws SQLException { metricRegistry = new MetricRegistry(); metricsReporter = Slf4jReporter.forRegistry(metricRegistry) .outputTo(LOGGER) .withLoggingLevel(Slf4jReporter.LoggingLevel.INFO) .build(); rawDataSource = H2DbUtil.createDataSource(); try (Connection connection = rawDataSource.getConnection()) { H2DbUtil.initTable(connection); } proxyFactory = MetricsSql.forRegistry(metricRegistry)
.withProxyFactory(new ReflectProxyFactory()).build();
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/CallableStatementProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.CallableStatement; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link CallableStatement} */ public class CallableStatementProxyHandler extends AbstractStatementProxyHandler<CallableStatement> { private final Query query; public CallableStatementProxyHandler(CallableStatement delegate, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, CallableStatement.class, proxyFactory, lifeTimerContext); this.query = query; }
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/CallableStatementProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.CallableStatement; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link CallableStatement} */ public class CallableStatementProxyHandler extends AbstractStatementProxyHandler<CallableStatement> { private final Query query; public CallableStatementProxyHandler(CallableStatement delegate, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, CallableStatement.class, proxyFactory, lifeTimerContext); this.query = query; }
protected final Object execute(MethodInvocation<CallableStatement> methodInvocation) throws Throwable {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/AbstractStatementProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.ResultSet; import java.sql.Statement; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Base JDBC proxy handler for Statements * * @param <T> Statement type */ public abstract class AbstractStatementProxyHandler<T extends Statement> extends JdbcProxyHandler<T> { public AbstractStatementProxyHandler(T delegate, Class<T> delegateType, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, delegateType, proxyFactory, lifeTimerContext); } @Override
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/AbstractStatementProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.ResultSet; import java.sql.Statement; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Base JDBC proxy handler for Statements * * @param <T> Statement type */ public abstract class AbstractStatementProxyHandler<T extends Statement> extends JdbcProxyHandler<T> { public AbstractStatementProxyHandler(T delegate, Class<T> delegateType, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, delegateType, proxyFactory, lifeTimerContext); } @Override
protected Object invoke(MethodInvocation<T> delegatingMethodInvocation) throws Throwable {
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/CGLibProxyFactoryTest.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // }
import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import static org.junit.Assert.assertNotNull;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Integration test between {@link CGLibProxyFactory} and {@link JdbcProxyFactory} */ public class CGLibProxyFactoryTest { private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; @Before public void setUp() { metricRegistry = new MetricRegistry();
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // Path: src/test/java/com/github/gquintana/metrics/sql/CGLibProxyFactoryTest.java import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import org.junit.Before; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import static org.junit.Assert.assertNotNull; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Integration test between {@link CGLibProxyFactory} and {@link JdbcProxyFactory} */ public class CGLibProxyFactoryTest { private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; @Before public void setUp() { metricRegistry = new MetricRegistry();
CGLibProxyFactory factory = new CGLibProxyFactory();
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/proxy/ProxyFactoryTest.java
// Path: src/test/java/com/github/gquintana/metrics/util/ParametersBuilder.java // public class ParametersBuilder { // private final Collection<Object[]> parameters = new ArrayList<>(); // public ParametersBuilder add(Object ... parameter) { // parameters.add(parameter); // return this; // } // public Collection<Object[]> build() { // return parameters; // } // }
import static org.junit.Assert.fail; import com.github.gquintana.metrics.util.ParametersBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals;
package com.github.gquintana.metrics.proxy; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ @RunWith(Parameterized.class) public class ProxyFactoryTest { private final ProxyFactory proxyFactory; private final Dummy dummy; private final DummyProxyHandler dummyProxyHandler; private static class DummyProxyHandler extends ProxyHandler<Dummy> { private final List<MethodInvocation<Dummy>> methodInvocations = new ArrayList<>(); public DummyProxyHandler(Dummy delegate) { super(delegate); } public List<MethodInvocation<Dummy>> getMethodInvocations() { return methodInvocations; } @Override protected Object invoke(MethodInvocation<Dummy> delegatingMethodInvocation) throws Throwable { methodInvocations.add(delegatingMethodInvocation); return super.invoke(delegatingMethodInvocation); } } public ProxyFactoryTest(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; dummyProxyHandler = new DummyProxyHandler(new DummyImpl()); dummy = proxyFactory.newProxy(dummyProxyHandler, new ProxyClass(Dummy.class.getClassLoader(), Dummy.class)); } @Parameterized.Parameters public static Collection<Object[]> getParameters() {
// Path: src/test/java/com/github/gquintana/metrics/util/ParametersBuilder.java // public class ParametersBuilder { // private final Collection<Object[]> parameters = new ArrayList<>(); // public ParametersBuilder add(Object ... parameter) { // parameters.add(parameter); // return this; // } // public Collection<Object[]> build() { // return parameters; // } // } // Path: src/test/java/com/github/gquintana/metrics/proxy/ProxyFactoryTest.java import static org.junit.Assert.fail; import com.github.gquintana.metrics.util.ParametersBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; package com.github.gquintana.metrics.proxy; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ @RunWith(Parameterized.class) public class ProxyFactoryTest { private final ProxyFactory proxyFactory; private final Dummy dummy; private final DummyProxyHandler dummyProxyHandler; private static class DummyProxyHandler extends ProxyHandler<Dummy> { private final List<MethodInvocation<Dummy>> methodInvocations = new ArrayList<>(); public DummyProxyHandler(Dummy delegate) { super(delegate); } public List<MethodInvocation<Dummy>> getMethodInvocations() { return methodInvocations; } @Override protected Object invoke(MethodInvocation<Dummy> delegatingMethodInvocation) throws Throwable { methodInvocations.add(delegatingMethodInvocation); return super.invoke(delegatingMethodInvocation); } } public ProxyFactoryTest(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; dummyProxyHandler = new DummyProxyHandler(new DummyImpl()); dummy = proxyFactory.newProxy(dummyProxyHandler, new ProxyClass(Dummy.class.getClassLoader(), Dummy.class)); } @Parameterized.Parameters public static Collection<Object[]> getParameters() {
return new ParametersBuilder()
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/Driver.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // }
import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import java.lang.reflect.Constructor; import java.sql.*; import java.util.List; import java.util.Properties; import java.util.logging.Logger;
continue; } int paramIndex = 0; for (Class<?> paramType : ctor.getParameterTypes()) { if (!paramType.isInstance(params[paramIndex])) { break; } paramIndex++; } if (paramIndex != params.length) { continue; } @SuppressWarnings("unchecked") Constructor<T> theCtor = (Constructor<T>) ctor; return theCtor.newInstance(params); } throw new SQLException("Constructor not found for " + clazz); } } catch (ReflectiveOperationException reflectiveOperationException) { throw new SQLException(reflectiveOperationException); } } @Override public Connection connect(String url, Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } DriverUrl driverUrl = DriverUrl.parse(url); MetricRegistry registry = getMetricRegistry(driverUrl);
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // Path: src/main/java/com/github/gquintana/metrics/sql/Driver.java import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import java.lang.reflect.Constructor; import java.sql.*; import java.util.List; import java.util.Properties; import java.util.logging.Logger; continue; } int paramIndex = 0; for (Class<?> paramType : ctor.getParameterTypes()) { if (!paramType.isInstance(params[paramIndex])) { break; } paramIndex++; } if (paramIndex != params.length) { continue; } @SuppressWarnings("unchecked") Constructor<T> theCtor = (Constructor<T>) ctor; return theCtor.newInstance(params); } throw new SQLException("Constructor not found for " + clazz); } } catch (ReflectiveOperationException reflectiveOperationException) { throw new SQLException(reflectiveOperationException); } } @Override public Connection connect(String url, Properties info) throws SQLException { if (!acceptsURL(url)) { return null; } DriverUrl driverUrl = DriverUrl.parse(url); MetricRegistry registry = getMetricRegistry(driverUrl);
ProxyFactory factory = newInstance(driverUrl.getProxyFactoryClass());
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/StatementProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.Statement; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link Statement} */ public class StatementProxyHandler extends AbstractStatementProxyHandler<Statement> { public StatementProxyHandler(Statement delegate, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, Statement.class, proxyFactory, lifeTimerContext); } @Override
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/StatementProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.Statement; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link Statement} */ public class StatementProxyHandler extends AbstractStatementProxyHandler<Statement> { public StatementProxyHandler(Statement delegate, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, Statement.class, proxyFactory, lifeTimerContext); } @Override
protected Object execute(MethodInvocation<Statement> methodInvocation) throws Throwable {
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/DriverUrlPropertiesTest.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * */ public class DriverUrlPropertiesTest { public static class CustomMetricNamingStrategy extends DefaultMetricNamingStrategy { } @Test public void testProperties() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE;metrics_driver=org.h2.Driver;metrics_proxy_factory=cglib;metrics_naming_strategy=" + CustomMetricNamingStrategy.class.getName() + ";metrics_database=test");
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/test/java/com/github/gquintana/metrics/sql/DriverUrlPropertiesTest.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * */ public class DriverUrlPropertiesTest { public static class CustomMetricNamingStrategy extends DefaultMetricNamingStrategy { } @Test public void testProperties() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE;metrics_driver=org.h2.Driver;metrics_proxy_factory=cglib;metrics_naming_strategy=" + CustomMetricNamingStrategy.class.getName() + ";metrics_database=test");
assertEquals(CGLibProxyFactory.class, driverUrl.getProxyFactoryClass());
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/DriverUrlPropertiesTest.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * */ public class DriverUrlPropertiesTest { public static class CustomMetricNamingStrategy extends DefaultMetricNamingStrategy { } @Test public void testProperties() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE;metrics_driver=org.h2.Driver;metrics_proxy_factory=cglib;metrics_naming_strategy=" + CustomMetricNamingStrategy.class.getName() + ";metrics_database=test"); assertEquals(CGLibProxyFactory.class, driverUrl.getProxyFactoryClass()); assertEquals(CustomMetricNamingStrategy.class, driverUrl.getNamingStrategyClass()); assertEquals("test", driverUrl.getDatabaseName()); assertEquals(org.h2.Driver.class, driverUrl.getDriverClass()); } @Test public void testPropertiesDefault() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE");
// Path: src/main/java/com/github/gquintana/metrics/proxy/CGLibProxyFactory.java // public class CGLibProxyFactory implements ProxyFactory { // // private final Map<ProxyClass, Class> proxyClasses = new ConcurrentHashMap<ProxyClass, Class>(); // private static final Class[] ADAPTER_CALLBACK_TYPES = new Class[]{ // AdapterMethodInterceptor.class, // AdapterLazyLoader.class // }; // // private static class AdapterCallbackFilter implements CallbackFilter { // // private final ProxyHandler.InvocationFilter invocationFilter; // // private AdapterCallbackFilter(ProxyHandler.InvocationFilter invocationFilter) { // this.invocationFilter = invocationFilter; // } // // @Override // public int accept(Method method) { // // 0 is AdapterMethodInterceptor // // 1 is AdapterLazyLoader // return invocationFilter.isIntercepted(method) ? 0 : 1; // } // } // // private static class AdapterMethodInterceptor implements MethodInterceptor { // // private final ProxyHandler proxyHandler; // // private AdapterMethodInterceptor(ProxyHandler proxyHandler) { // this.proxyHandler = proxyHandler; // } // // @Override // public Object intercept(Object proxy, Method method, Object[] arguments, MethodProxy methodProxy) throws Throwable { // return proxyHandler.invoke(proxy, method, arguments); // } // } // // private static class AdapterLazyLoader<T> implements LazyLoader { // // private final T delegate; // // private AdapterLazyLoader(T delegate) { // this.delegate = delegate; // } // // @Override // public T loadObject() { // return delegate; // } // } // // private Class getProxyClass(ProxyHandler<?> proxyHandler, ProxyClass proxyClass) { // Class clazz = proxyClasses.get(proxyClass); // if (clazz == null) { // Enhancer enhancer = new Enhancer(); // enhancer.setCallbackFilter(new AdapterCallbackFilter(proxyHandler.getInvocationFilter())); // enhancer.setCallbackTypes(ADAPTER_CALLBACK_TYPES); // enhancer.setClassLoader(proxyClass.getClassLoader()); // enhancer.setInterfaces(proxyClass.getInterfaces()); // clazz = enhancer.createClass(); // proxyClasses.put(proxyClass, clazz); // } // return clazz; // } // // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // try { // Object proxy = getProxyClass(proxyHandler, proxyClass).newInstance(); // ((Factory) proxy).setCallbacks(new Callback[]{ // new AdapterMethodInterceptor(proxyHandler), // new AdapterLazyLoader<Object>(proxyHandler.getDelegate()) // }); // return (T) proxy; // } catch (ReflectiveOperationException e) { // throw new ProxyException(e); // } // } // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/test/java/com/github/gquintana/metrics/sql/DriverUrlPropertiesTest.java import com.github.gquintana.metrics.proxy.CGLibProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * */ public class DriverUrlPropertiesTest { public static class CustomMetricNamingStrategy extends DefaultMetricNamingStrategy { } @Test public void testProperties() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE;metrics_driver=org.h2.Driver;metrics_proxy_factory=cglib;metrics_naming_strategy=" + CustomMetricNamingStrategy.class.getName() + ";metrics_database=test"); assertEquals(CGLibProxyFactory.class, driverUrl.getProxyFactoryClass()); assertEquals(CustomMetricNamingStrategy.class, driverUrl.getNamingStrategyClass()); assertEquals("test", driverUrl.getDatabaseName()); assertEquals(org.h2.Driver.class, driverUrl.getDriverClass()); } @Test public void testPropertiesDefault() { DriverUrl driverUrl = DriverUrl.parse("jdbc:metrics:h2:~/test;AUTO_SERVER=TRUE;;AUTO_RECONNECT=TRUE");
assertEquals(ReflectProxyFactory.class, driverUrl.getProxyFactoryClass());
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/DataSourceProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import javax.sql.DataSource; import java.sql.Connection; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link DataSource} */ public class DataSourceProxyHandler extends JdbcProxyHandler<DataSource> { public DataSourceProxyHandler(DataSource delegate, JdbcProxyFactory proxyFactory) { super(delegate, DataSource.class, proxyFactory, null); } @Override
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/DataSourceProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import javax.sql.DataSource; import java.sql.Connection; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link DataSource} */ public class DataSourceProxyHandler extends JdbcProxyHandler<DataSource> { public DataSourceProxyHandler(DataSource delegate, JdbcProxyFactory proxyFactory) { super(delegate, DataSource.class, proxyFactory, null); } @Override
protected Object invoke(MethodInvocation<DataSource> methodInvocation) throws Throwable {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/PreparedStatementProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.PreparedStatement; import com.codahale.metrics.Timer;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC proxy handler for {@link PreparedStatement} */ public class PreparedStatementProxyHandler extends AbstractStatementProxyHandler<PreparedStatement> { private final Query query; public PreparedStatementProxyHandler(PreparedStatement delegate, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, PreparedStatement.class, proxyFactory, lifeTimerContext); this.query = query; }
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/PreparedStatementProxyHandler.java import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.PreparedStatement; import com.codahale.metrics.Timer; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC proxy handler for {@link PreparedStatement} */ public class PreparedStatementProxyHandler extends AbstractStatementProxyHandler<PreparedStatement> { private final Query query; public PreparedStatementProxyHandler(PreparedStatement delegate, JdbcProxyFactory proxyFactory, Query query, Timer.Context lifeTimerContext) { super(delegate, PreparedStatement.class, proxyFactory, lifeTimerContext); this.query = query; }
protected final Object execute(MethodInvocation<PreparedStatement> methodInvocation) throws Throwable {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/MetricsSql.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.DataSource; import java.sql.*;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metrics SQL initializing class */ public class MetricsSql { /** * Builder of {@link JdbcProxyFactory} */ public static class Builder { private final MetricRegistry registry; private MetricNamingStrategy namingStrategy = new DefaultMetricNamingStrategy();
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/MetricsSql.java import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.DataSource; import java.sql.*; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metrics SQL initializing class */ public class MetricsSql { /** * Builder of {@link JdbcProxyFactory} */ public static class Builder { private final MetricRegistry registry; private MetricNamingStrategy namingStrategy = new DefaultMetricNamingStrategy();
private ProxyFactory proxyFactory = new ReflectProxyFactory();
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/MetricsSql.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.DataSource; import java.sql.*;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metrics SQL initializing class */ public class MetricsSql { /** * Builder of {@link JdbcProxyFactory} */ public static class Builder { private final MetricRegistry registry; private MetricNamingStrategy namingStrategy = new DefaultMetricNamingStrategy();
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/MetricsSql.java import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.DataSource; import java.sql.*; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Metrics SQL initializing class */ public class MetricsSql { /** * Builder of {@link JdbcProxyFactory} */ public static class Builder { private final MetricRegistry registry; private MetricNamingStrategy namingStrategy = new DefaultMetricNamingStrategy();
private ProxyFactory proxyFactory = new ReflectProxyFactory();
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/JmxReportingTest.java
// Path: src/main/java/com/github/gquintana/metrics/util/SqlObjectNameFactory.java // public class SqlObjectNameFactory implements ObjectNameFactory { // private final ObjectNameFactory defaultObjectFactory; // // public SqlObjectNameFactory(ObjectNameFactory defaultObjectNameFactory) { // this.defaultObjectFactory = defaultObjectNameFactory; // } // // public SqlObjectNameFactory() { // this.defaultObjectFactory = new DefaultObjectNameFactory(); // } // // private static final Pattern PATTERN = Pattern.compile( // "(java\\.sql" // Package // + "\\.[A-Z]\\w+)" // Class // + "\\.(\\w+)" // Database // + "(?:\\.\\[([^]]*)\\])?" // SQL Query // + "(?:\\.(\\w+))?"); // Event // @Override // public ObjectName createName(String type, String domain, String name) { // Matcher matcher = PATTERN.matcher(name); // ObjectName objectName = null; // if (matcher.matches()) { // String className = matcher.group(1); // String database = matcher.group(2); // String sql = matcher.group(3); // String event = matcher.group(4); // Hashtable<String, String> props = new Hashtable<>(); // props.put("class", className); // props.put("database", database); // if (sql!=null) { // // , and \ are not allowed // props.put("sql", sql.replaceAll("[:=*?,\\n\\\\]", " ").replaceAll("[\\s]+", " ")); // } // if (event!=null) { // props.put("event", event); // } // if (type!=null) { // props.put("metricType", type); // } // try { // objectName = new ObjectName(domain, props); // } catch (MalformedObjectNameException malformedObjectNameException) { // } // } // if (objectName == null) { // objectName = defaultObjectFactory.createName(type, domain, name); // } // return objectName; // } // // }
import java.sql.*; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.util.SqlObjectNameFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.management.MBeanServer; import javax.sql.DataSource; import java.lang.management.ManagementFactory;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Test the integration between Metric SQL and the JMX Reporter */ public class JmxReportingTest { private MBeanServer mBeanServer; private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; private DataSource rawDataSource; private DataSource dataSource; private JmxReporter jmxReporter; @Before public void setUp() throws SQLException { mBeanServer=ManagementFactory.getPlatformMBeanServer(); metricRegistry = new MetricRegistry(); jmxReporter = JmxReporter.forRegistry(metricRegistry) .registerWith(mBeanServer)
// Path: src/main/java/com/github/gquintana/metrics/util/SqlObjectNameFactory.java // public class SqlObjectNameFactory implements ObjectNameFactory { // private final ObjectNameFactory defaultObjectFactory; // // public SqlObjectNameFactory(ObjectNameFactory defaultObjectNameFactory) { // this.defaultObjectFactory = defaultObjectNameFactory; // } // // public SqlObjectNameFactory() { // this.defaultObjectFactory = new DefaultObjectNameFactory(); // } // // private static final Pattern PATTERN = Pattern.compile( // "(java\\.sql" // Package // + "\\.[A-Z]\\w+)" // Class // + "\\.(\\w+)" // Database // + "(?:\\.\\[([^]]*)\\])?" // SQL Query // + "(?:\\.(\\w+))?"); // Event // @Override // public ObjectName createName(String type, String domain, String name) { // Matcher matcher = PATTERN.matcher(name); // ObjectName objectName = null; // if (matcher.matches()) { // String className = matcher.group(1); // String database = matcher.group(2); // String sql = matcher.group(3); // String event = matcher.group(4); // Hashtable<String, String> props = new Hashtable<>(); // props.put("class", className); // props.put("database", database); // if (sql!=null) { // // , and \ are not allowed // props.put("sql", sql.replaceAll("[:=*?,\\n\\\\]", " ").replaceAll("[\\s]+", " ")); // } // if (event!=null) { // props.put("event", event); // } // if (type!=null) { // props.put("metricType", type); // } // try { // objectName = new ObjectName(domain, props); // } catch (MalformedObjectNameException malformedObjectNameException) { // } // } // if (objectName == null) { // objectName = defaultObjectFactory.createName(type, domain, name); // } // return objectName; // } // // } // Path: src/test/java/com/github/gquintana/metrics/sql/JmxReportingTest.java import java.sql.*; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.MetricRegistry; import com.github.gquintana.metrics.util.SqlObjectNameFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.management.MBeanServer; import javax.sql.DataSource; import java.lang.management.ManagementFactory; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Test the integration between Metric SQL and the JMX Reporter */ public class JmxReportingTest { private MBeanServer mBeanServer; private MetricRegistry metricRegistry; private JdbcProxyFactory proxyFactory; private DataSource rawDataSource; private DataSource dataSource; private JmxReporter jmxReporter; @Before public void setUp() throws SQLException { mBeanServer=ManagementFactory.getPlatformMBeanServer(); metricRegistry = new MetricRegistry(); jmxReporter = JmxReporter.forRegistry(metricRegistry) .registerWith(mBeanServer)
.createsObjectNamesWith(new SqlObjectNameFactory())
gquintana/metrics-sql
src/test/java/com/github/gquintana/metrics/sql/DriverUrlParseTest.java
// Path: src/test/java/com/github/gquintana/metrics/util/ParametersBuilder.java // public class ParametersBuilder { // private final Collection<Object[]> parameters = new ArrayList<>(); // public ParametersBuilder add(Object ... parameter) { // parameters.add(parameter); // return this; // } // public Collection<Object[]> build() { // return parameters; // } // }
import com.github.gquintana.metrics.util.ParametersBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Test driver URL parsing */ @RunWith(Parameterized.class) public class DriverUrlParseTest { private final String rawUrl; private final String cleanUrl; private final String databaseType; private final Properties properties; public DriverUrlParseTest(String rawUrl, String cleanUrl, String databaseType, Properties properties) { this.rawUrl = rawUrl; this.cleanUrl = cleanUrl; this.databaseType = databaseType; this.properties = properties; } @Parameterized.Parameters public static Collection<Object[]> getParameters() { Properties properties1 = new Properties(); properties1.setProperty("metrics_key", "val");
// Path: src/test/java/com/github/gquintana/metrics/util/ParametersBuilder.java // public class ParametersBuilder { // private final Collection<Object[]> parameters = new ArrayList<>(); // public ParametersBuilder add(Object ... parameter) { // parameters.add(parameter); // return this; // } // public Collection<Object[]> build() { // return parameters; // } // } // Path: src/test/java/com/github/gquintana/metrics/sql/DriverUrlParseTest.java import com.github.gquintana.metrics.util.ParametersBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Collection; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Test driver URL parsing */ @RunWith(Parameterized.class) public class DriverUrlParseTest { private final String rawUrl; private final String cleanUrl; private final String databaseType; private final Properties properties; public DriverUrlParseTest(String rawUrl, String cleanUrl, String databaseType, Properties properties) { this.rawUrl = rawUrl; this.cleanUrl = cleanUrl; this.databaseType = databaseType; this.properties = properties; } @Parameterized.Parameters public static Collection<Object[]> getParameters() { Properties properties1 = new Properties(); properties1.setProperty("metrics_key", "val");
return new ParametersBuilder()
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/ConnectionProxyHandler.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // }
import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link Connection} */ public class ConnectionProxyHandler extends JdbcProxyHandler<Connection> { /** * Main constructor * * @param delegate Wrapped connection * @param proxyFactory Strategy to create proxies * @param lifeTimerContext Started timed corresponding to connection life */ public ConnectionProxyHandler(Connection delegate, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, Connection.class, proxyFactory, lifeTimerContext); } @Override
// Path: src/main/java/com/github/gquintana/metrics/proxy/MethodInvocation.java // public final class MethodInvocation<T> { // // /** // * Target (real) object // */ // private final T delegate; // /** // * Proxy // */ // private final Object proxy; // /** // * Method // */ // private final Method method; // /** // * Invocation arguments // */ // private final Object[] args; // // public MethodInvocation(T target, Object proxy, Method method, Object... args) { // this.delegate = target; // this.proxy = proxy; // this.method = method; // this.args = args; // } // // public int getArgCount() { // return args == null ? 0 : args.length; // } // // public Object getArgAt(int argIndex) { // return args[argIndex]; // } // // public <R> R getArgAt(int argIndex, Class<R> argType) { // return argType.cast(getArgAt(argIndex)); // } // // public String getMethodName() { // return method.getName(); // } // // public Object proceed() throws Throwable { // try { // return method.invoke(delegate, args); // } catch(InvocationTargetException e) { // throw e.getTargetException(); // } // } // // } // Path: src/main/java/com/github/gquintana/metrics/sql/ConnectionProxyHandler.java import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.MethodInvocation; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Statement; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * JDBC Proxy handler for {@link Connection} */ public class ConnectionProxyHandler extends JdbcProxyHandler<Connection> { /** * Main constructor * * @param delegate Wrapped connection * @param proxyFactory Strategy to create proxies * @param lifeTimerContext Started timed corresponding to connection life */ public ConnectionProxyHandler(Connection delegate, JdbcProxyFactory proxyFactory, Timer.Context lifeTimerContext) { super(delegate, Connection.class, proxyFactory, lifeTimerContext); } @Override
protected Object invoke(MethodInvocation<Connection> delegatingMethodInvocation) throws Throwable {
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/JdbcProxyFactory.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.*; import javax.sql.rowset.*; import java.sql.*;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Factory of {@code JdbcProxyHandler} sub classes, central class of Metrics SQL. * It can be used to wrap any JDBC component (connection, statement, * result set...). */ public class JdbcProxyFactory { /** * Timer manager */ private final MetricHelper metricHelper; /** * Proxy factory */
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/JdbcProxyFactory.java import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.*; import javax.sql.rowset.*; import java.sql.*; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Factory of {@code JdbcProxyHandler} sub classes, central class of Metrics SQL. * It can be used to wrap any JDBC component (connection, statement, * result set...). */ public class JdbcProxyFactory { /** * Timer manager */ private final MetricHelper metricHelper; /** * Proxy factory */
private final ProxyFactory proxyFactory;
gquintana/metrics-sql
src/main/java/com/github/gquintana/metrics/sql/JdbcProxyFactory.java
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // }
import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.*; import javax.sql.rowset.*; import java.sql.*;
package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Factory of {@code JdbcProxyHandler} sub classes, central class of Metrics SQL. * It can be used to wrap any JDBC component (connection, statement, * result set...). */ public class JdbcProxyFactory { /** * Timer manager */ private final MetricHelper metricHelper; /** * Proxy factory */ private final ProxyFactory proxyFactory; /** * Constructor using default {@link ReflectProxyFactory} and default {@link DefaultMetricNamingStrategy} * @param metricRegistry Metric registry to store metrics */ public JdbcProxyFactory(MetricRegistry metricRegistry) { this(metricRegistry, new DefaultMetricNamingStrategy()); } /** * Constructor * * @param registry Registry storing metrics * @param namingStrategy Naming strategy used to get metrics from SQL */ public JdbcProxyFactory(MetricRegistry registry, MetricNamingStrategy namingStrategy) {
// Path: src/main/java/com/github/gquintana/metrics/proxy/ProxyFactory.java // public interface ProxyFactory { // /** // * Create a proxy using given classloader and interfaces // * // * @param proxyHandler Proxy invocation handler // * @param proxyClass Class loader + Interfaces to implement // * @param <T> Proxy type // * @return Proxy // */ // <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass); // // } // // Path: src/main/java/com/github/gquintana/metrics/proxy/ReflectProxyFactory.java // public class ReflectProxyFactory implements ProxyFactory { // /** // * {@inheritDoc} // */ // @Override // public <T> T newProxy(ProxyHandler<T> proxyHandler, ProxyClass proxyClass) { // return (T) Proxy.newProxyInstance(proxyClass.getClassLoader(), proxyClass.getInterfaces(), proxyHandler); // } // } // Path: src/main/java/com/github/gquintana/metrics/sql/JdbcProxyFactory.java import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.github.gquintana.metrics.proxy.ProxyFactory; import com.github.gquintana.metrics.proxy.ReflectProxyFactory; import javax.sql.*; import javax.sql.rowset.*; import java.sql.*; package com.github.gquintana.metrics.sql; /* * #%L * Metrics SQL * %% * Copyright (C) 2014 Open-Source * %% * 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. * #L% */ /** * Factory of {@code JdbcProxyHandler} sub classes, central class of Metrics SQL. * It can be used to wrap any JDBC component (connection, statement, * result set...). */ public class JdbcProxyFactory { /** * Timer manager */ private final MetricHelper metricHelper; /** * Proxy factory */ private final ProxyFactory proxyFactory; /** * Constructor using default {@link ReflectProxyFactory} and default {@link DefaultMetricNamingStrategy} * @param metricRegistry Metric registry to store metrics */ public JdbcProxyFactory(MetricRegistry metricRegistry) { this(metricRegistry, new DefaultMetricNamingStrategy()); } /** * Constructor * * @param registry Registry storing metrics * @param namingStrategy Naming strategy used to get metrics from SQL */ public JdbcProxyFactory(MetricRegistry registry, MetricNamingStrategy namingStrategy) {
this(registry, namingStrategy, new ReflectProxyFactory());
dmfs/jdav
src/org/dmfs/dav/rfc4791/filter/PropFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
{ this.name = name; this.isNotDefined = false; this.timeRange = timeRange; this.textMatch = null; this.filters = filters; } /** * Creates a filter that matches a property by a specific text value and optionally a list of {@link ParamFilter}s. * * @param name * The name of the property to match. * @param textMatch * The text filter. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, TextMatch textMatch, ParamFilter... filters) { this.name = name; this.isNotDefined = false; this.timeRange = null; this.textMatch = textMatch; this.filters = filters; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc4791/filter/PropFilter.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; { this.name = name; this.isNotDefined = false; this.timeRange = timeRange; this.textMatch = null; this.filters = filters; } /** * Creates a filter that matches a property by a specific text value and optionally a list of {@link ParamFilter}s. * * @param name * The name of the property to match. * @param textMatch * The text filter. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, TextMatch textMatch, ParamFilter... filters) { this.name = name; this.isNotDefined = false; this.timeRange = null; this.textMatch = textMatch; this.filters = filters; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc4791/filter/CompFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
/** * Creates a filter for a spcecific component with subfilters and a time range filter to match. * * @param name * the name of the component to match, must not be empty. * @param timeRange * the {@link TimeRange} to match. May be <code>null</code>. * @param filters * Optional subfilters to match. */ public CompFilter(String name, TimeRange timeRange, StructuredFilter... filters) { if (name == null) { throw new NullPointerException("the component name of a comp filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the component name of a comp filter must not be empty"); } this.name = name; this.isNotDefined = false; this.timeRange = timeRange; this.filters = filters; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc4791/filter/CompFilter.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; /** * Creates a filter for a spcecific component with subfilters and a time range filter to match. * * @param name * the name of the component to match, must not be empty. * @param timeRange * the {@link TimeRange} to match. May be <code>null</code>. * @param filters * Optional subfilters to match. */ public CompFilter(String name, TimeRange timeRange, StructuredFilter... filters) { if (name == null) { throw new NullPointerException("the component name of a comp filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the component name of a comp filter must not be empty"); } this.name = name; this.isNotDefined = false; this.timeRange = timeRange; this.filters = filters; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc6352/filter/TextMatch.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
* @param caseInsensitive * Perform case-insensitive matching using the default collation {@link #COLLATION_I_UNICODE_CASEMAP}. */ public TextMatch(String value, boolean negate, boolean caseInsensitive) { this(value, negate, caseInsensitive ? COLLATION_I_UNICODE_CASEMAP : null, MatchType.equals); } /** * Create a text-match filter. * * @param value * The filter value. * @param negate * Negate the search condition (i.e. return only results that do not match the value). * @param collation * The collation to use, see <a href="http://tools.ietf.org/html/rfc4790">RFC 4790</a> and <a * href="http://tools.ietf.org/html/rfc4791#section-7.5.1">supported-collation-set</a>. */ public TextMatch(String value, boolean negate, String collation, MatchType matchType) { this.value = value; this.negate = negate; this.collation = collation; this.matchType = matchType; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc6352/filter/TextMatch.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; * @param caseInsensitive * Perform case-insensitive matching using the default collation {@link #COLLATION_I_UNICODE_CASEMAP}. */ public TextMatch(String value, boolean negate, boolean caseInsensitive) { this(value, negate, caseInsensitive ? COLLATION_I_UNICODE_CASEMAP : null, MatchType.equals); } /** * Create a text-match filter. * * @param value * The filter value. * @param negate * Negate the search condition (i.e. return only results that do not match the value). * @param collation * The collation to use, see <a href="http://tools.ietf.org/html/rfc4790">RFC 4790</a> and <a * href="http://tools.ietf.org/html/rfc4791#section-7.5.1">supported-collation-set</a>. */ public TextMatch(String value, boolean negate, String collation, MatchType matchType) { this.value = value; this.negate = negate; this.collation = collation; this.matchType = matchType; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc6352/filter/ParamFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
this.isNotDefined = isNotDefined; this.textMatch = null; } /** * Create a filter that matches the value of a parameter. * * @param name * The name of the parameter, must not be empty. * @param textMatch * The filter for the text. */ public ParamFilter(String name, TextMatch textMatch) { if (name == null) { throw new NullPointerException("the parameter name of a param filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the parameter name of a param filter must not be empty"); } this.name = name; this.isNotDefined = false; this.textMatch = textMatch; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc6352/filter/ParamFilter.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; this.isNotDefined = isNotDefined; this.textMatch = null; } /** * Create a filter that matches the value of a parameter. * * @param name * The name of the parameter, must not be empty. * @param textMatch * The filter for the text. */ public ParamFilter(String name, TextMatch textMatch) { if (name == null) { throw new NullPointerException("the parameter name of a param filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the parameter name of a param filter must not be empty"); } this.name = name; this.isNotDefined = false; this.textMatch = textMatch; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc4791/filter/TimeRange.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.rfc5545.DateTime; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter;
if (start != null) { if (start.isFloating()) { throw new IllegalArgumentException("start date must have absolute time"); } this.start = new DateTime(DateTime.GREGORIAN_CALENDAR_SCALE, DateTime.UTC, start); } else { this.start = null; } if (end != null) { if (end.isFloating()) { throw new IllegalArgumentException("end date must have absolute time"); } this.end = new DateTime(DateTime.GREGORIAN_CALENDAR_SCALE, DateTime.UTC, end); } else { this.end = null; } } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc4791/filter/TimeRange.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.rfc5545.DateTime; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; if (start != null) { if (start.isFloating()) { throw new IllegalArgumentException("start date must have absolute time"); } this.start = new DateTime(DateTime.GREGORIAN_CALENDAR_SCALE, DateTime.UTC, start); } else { this.start = null; } if (end != null) { if (end.isFloating()) { throw new IllegalArgumentException("end date must have absolute time"); } this.end = new DateTime(DateTime.GREGORIAN_CALENDAR_SCALE, DateTime.UTC, end); } else { this.end = null; } } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc4791/filter/ParamFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
this.isNotDefined = isNotDefined; this.textMatch = null; } /** * Create a filter that matches the value of a parameter. * * @param name * The name of the parameter, must not be empty. * @param textMatch * The filter for the text. */ public ParamFilter(String name, TextMatch textMatch) { if (name == null) { throw new NullPointerException("the parameter name of a param filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the parameter name of a param filter must not be empty"); } this.name = name; this.isNotDefined = false; this.textMatch = textMatch; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc4791/filter/ParamFilter.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; this.isNotDefined = isNotDefined; this.textMatch = null; } /** * Create a filter that matches the value of a parameter. * * @param name * The name of the parameter, must not be empty. * @param textMatch * The filter for the text. */ public ParamFilter(String name, TextMatch textMatch) { if (name == null) { throw new NullPointerException("the parameter name of a param filter must not be null"); } if (name.length() == 0) { throw new IllegalArgumentException("the parameter name of a param filter must not be empty"); } this.name = name; this.isNotDefined = false; this.textMatch = textMatch; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc4918/PropStat.java
// Path: src/org/dmfs/dav/DavParserContext.java // public class DavParserContext extends ParserContext // { // private boolean mStrict = true; // private boolean mKeepNotFoundProperties = false; // // // /** // * Create a new {@link DavParserContext}. // */ // public DavParserContext() // { // mStrict = true; // } // // // /** // * Enable or disable strict parsing. Strict parsing will throw an error in some cases when the response is malformed. If strict parsing is not enabled the // * parser is supposed to make assumptions about the intent and continue if possible. // * // * @param strict // * <code>true</code> to be strict with errors, <code>false</code> otherwise. // * @return // */ // public DavParserContext setStrict(boolean strict) // { // mStrict = strict; // return this; // } // // // /** // * Return whether strict parsing has been requested or not. // * // * @return <code>true</code> to be strict with issues. // */ // public boolean isStrict() // { // return mStrict; // } // // // /** // * Set whether to allow dropping propstat elements with status {@link HttpStatus#NOT_FOUND}. In many cases there is no benefit in keeping them, so the // * default is not to store them. // * // * @param keepNotFoundProperties // * <code>true</code> to keep propstat elements with status {@link HttpStatus#NOT_FOUND}. // */ // public DavParserContext setKeepNotFoundProperties(boolean keepNotFoundProperties) // { // mKeepNotFoundProperties = keepNotFoundProperties; // return this; // } // // // /** // * Returns whether to keep properties with status {@link HttpStatus#NOT_FOUND} or not. // * // * @return <code>true</code> to keep such properties, <code>false</code> otherwise. // */ // public boolean getKeepNotFoundProperties() // { // return mKeepNotFoundProperties; // } // }
import org.dmfs.xmlobjects.pull.Recyclable; import org.dmfs.xmlobjects.pull.XmlObjectPullParserException; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Set; import org.dmfs.dav.DavParserContext; import org.dmfs.httpclientinterfaces.HttpStatus; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.builder.IObjectBuilder; import org.dmfs.xmlobjects.pull.ParserContext;
@Override public <V> PropStat update(ElementDescriptor<PropStat> descriptor, PropStat object, ElementDescriptor<V> childDescriptor, V child, ParserContext context) throws XmlObjectPullParserException { if (childDescriptor == WebDav.PROP) { // recycle old property map, if any context.recycle(WebDav.PROP, object.mProperties); // set new property list object.mProperties = (Map<ElementDescriptor<?>, Object>) child; } else if (childDescriptor == WebDav.STATUS) { object.mStatus = (Integer) child; } else if (childDescriptor == WebDav.ERROR) { object.mError = (Error) child; } else if (childDescriptor == WebDav.RESPONSEDESCRIPTION) { object.mResponseDescription = child.toString(); } return object; }; @Override public PropStat finish(ElementDescriptor<PropStat> descriptor, PropStat object, ParserContext context) throws XmlObjectPullParserException {
// Path: src/org/dmfs/dav/DavParserContext.java // public class DavParserContext extends ParserContext // { // private boolean mStrict = true; // private boolean mKeepNotFoundProperties = false; // // // /** // * Create a new {@link DavParserContext}. // */ // public DavParserContext() // { // mStrict = true; // } // // // /** // * Enable or disable strict parsing. Strict parsing will throw an error in some cases when the response is malformed. If strict parsing is not enabled the // * parser is supposed to make assumptions about the intent and continue if possible. // * // * @param strict // * <code>true</code> to be strict with errors, <code>false</code> otherwise. // * @return // */ // public DavParserContext setStrict(boolean strict) // { // mStrict = strict; // return this; // } // // // /** // * Return whether strict parsing has been requested or not. // * // * @return <code>true</code> to be strict with issues. // */ // public boolean isStrict() // { // return mStrict; // } // // // /** // * Set whether to allow dropping propstat elements with status {@link HttpStatus#NOT_FOUND}. In many cases there is no benefit in keeping them, so the // * default is not to store them. // * // * @param keepNotFoundProperties // * <code>true</code> to keep propstat elements with status {@link HttpStatus#NOT_FOUND}. // */ // public DavParserContext setKeepNotFoundProperties(boolean keepNotFoundProperties) // { // mKeepNotFoundProperties = keepNotFoundProperties; // return this; // } // // // /** // * Returns whether to keep properties with status {@link HttpStatus#NOT_FOUND} or not. // * // * @return <code>true</code> to keep such properties, <code>false</code> otherwise. // */ // public boolean getKeepNotFoundProperties() // { // return mKeepNotFoundProperties; // } // } // Path: src/org/dmfs/dav/rfc4918/PropStat.java import org.dmfs.xmlobjects.pull.Recyclable; import org.dmfs.xmlobjects.pull.XmlObjectPullParserException; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Set; import org.dmfs.dav.DavParserContext; import org.dmfs.httpclientinterfaces.HttpStatus; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.builder.IObjectBuilder; import org.dmfs.xmlobjects.pull.ParserContext; @Override public <V> PropStat update(ElementDescriptor<PropStat> descriptor, PropStat object, ElementDescriptor<V> childDescriptor, V child, ParserContext context) throws XmlObjectPullParserException { if (childDescriptor == WebDav.PROP) { // recycle old property map, if any context.recycle(WebDav.PROP, object.mProperties); // set new property list object.mProperties = (Map<ElementDescriptor<?>, Object>) child; } else if (childDescriptor == WebDav.STATUS) { object.mStatus = (Integer) child; } else if (childDescriptor == WebDav.ERROR) { object.mError = (Error) child; } else if (childDescriptor == WebDav.RESPONSEDESCRIPTION) { object.mResponseDescription = child.toString(); } return object; }; @Override public PropStat finish(ElementDescriptor<PropStat> descriptor, PropStat object, ParserContext context) throws XmlObjectPullParserException {
boolean strict = !(context instanceof DavParserContext) || ((DavParserContext) context).isStrict();
dmfs/jdav
src/org/dmfs/dav/rfc4918/Response.java
// Path: src/org/dmfs/dav/DavParserContext.java // public class DavParserContext extends ParserContext // { // private boolean mStrict = true; // private boolean mKeepNotFoundProperties = false; // // // /** // * Create a new {@link DavParserContext}. // */ // public DavParserContext() // { // mStrict = true; // } // // // /** // * Enable or disable strict parsing. Strict parsing will throw an error in some cases when the response is malformed. If strict parsing is not enabled the // * parser is supposed to make assumptions about the intent and continue if possible. // * // * @param strict // * <code>true</code> to be strict with errors, <code>false</code> otherwise. // * @return // */ // public DavParserContext setStrict(boolean strict) // { // mStrict = strict; // return this; // } // // // /** // * Return whether strict parsing has been requested or not. // * // * @return <code>true</code> to be strict with issues. // */ // public boolean isStrict() // { // return mStrict; // } // // // /** // * Set whether to allow dropping propstat elements with status {@link HttpStatus#NOT_FOUND}. In many cases there is no benefit in keeping them, so the // * default is not to store them. // * // * @param keepNotFoundProperties // * <code>true</code> to keep propstat elements with status {@link HttpStatus#NOT_FOUND}. // */ // public DavParserContext setKeepNotFoundProperties(boolean keepNotFoundProperties) // { // mKeepNotFoundProperties = keepNotFoundProperties; // return this; // } // // // /** // * Returns whether to keep properties with status {@link HttpStatus#NOT_FOUND} or not. // * // * @return <code>true</code> to keep such properties, <code>false</code> otherwise. // */ // public boolean getKeepNotFoundProperties() // { // return mKeepNotFoundProperties; // } // }
import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.dmfs.dav.DavParserContext; import org.dmfs.httpclientinterfaces.HttpStatus; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.builder.IObjectBuilder; import org.dmfs.xmlobjects.pull.ParserContext; import org.dmfs.xmlobjects.pull.Recyclable; import org.dmfs.xmlobjects.pull.XmlObjectPullParserException; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
/* * Copyright (C) 2014 Marten Gajda <marten@dmfs.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.dav.rfc4918; /** * This class represents a multistatus <code>response</code> element as defined in <a href="http://tools.ietf.org/html/rfc4918#section-14.24">RFC 4918 section * 14.24</a>. * * @author Marten Gajda <marten@dmfs.org> */ public class Response implements Recyclable { /** * The status code if there was no status element. */ public final static int STATUS_NONE = -1; /** * An {@link IXmlObjectBuilder} for {@link Response} elements. */ public final static IObjectBuilder<Response> BUILDER = new AbstractObjectBuilder<Response>() { @Override public Response get(ElementDescriptor<Response> descriptor, Response recycle, ParserContext context) throws XmlObjectPullParserException { if (recycle != null) { recycle.recycle(); return recycle; } return new Response(); }; @Override public <V> Response update(ElementDescriptor<Response> descriptor, Response object, ElementDescriptor<V> childDescriptor, V child, ParserContext context) throws XmlObjectPullParserException { if (childDescriptor == WebDav.PROPSTAT) { PropStat propStat = (PropStat) child;
// Path: src/org/dmfs/dav/DavParserContext.java // public class DavParserContext extends ParserContext // { // private boolean mStrict = true; // private boolean mKeepNotFoundProperties = false; // // // /** // * Create a new {@link DavParserContext}. // */ // public DavParserContext() // { // mStrict = true; // } // // // /** // * Enable or disable strict parsing. Strict parsing will throw an error in some cases when the response is malformed. If strict parsing is not enabled the // * parser is supposed to make assumptions about the intent and continue if possible. // * // * @param strict // * <code>true</code> to be strict with errors, <code>false</code> otherwise. // * @return // */ // public DavParserContext setStrict(boolean strict) // { // mStrict = strict; // return this; // } // // // /** // * Return whether strict parsing has been requested or not. // * // * @return <code>true</code> to be strict with issues. // */ // public boolean isStrict() // { // return mStrict; // } // // // /** // * Set whether to allow dropping propstat elements with status {@link HttpStatus#NOT_FOUND}. In many cases there is no benefit in keeping them, so the // * default is not to store them. // * // * @param keepNotFoundProperties // * <code>true</code> to keep propstat elements with status {@link HttpStatus#NOT_FOUND}. // */ // public DavParserContext setKeepNotFoundProperties(boolean keepNotFoundProperties) // { // mKeepNotFoundProperties = keepNotFoundProperties; // return this; // } // // // /** // * Returns whether to keep properties with status {@link HttpStatus#NOT_FOUND} or not. // * // * @return <code>true</code> to keep such properties, <code>false</code> otherwise. // */ // public boolean getKeepNotFoundProperties() // { // return mKeepNotFoundProperties; // } // } // Path: src/org/dmfs/dav/rfc4918/Response.java import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.dmfs.dav.DavParserContext; import org.dmfs.httpclientinterfaces.HttpStatus; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.builder.IObjectBuilder; import org.dmfs.xmlobjects.pull.ParserContext; import org.dmfs.xmlobjects.pull.Recyclable; import org.dmfs.xmlobjects.pull.XmlObjectPullParserException; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; /* * Copyright (C) 2014 Marten Gajda <marten@dmfs.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.dav.rfc4918; /** * This class represents a multistatus <code>response</code> element as defined in <a href="http://tools.ietf.org/html/rfc4918#section-14.24">RFC 4918 section * 14.24</a>. * * @author Marten Gajda <marten@dmfs.org> */ public class Response implements Recyclable { /** * The status code if there was no status element. */ public final static int STATUS_NONE = -1; /** * An {@link IXmlObjectBuilder} for {@link Response} elements. */ public final static IObjectBuilder<Response> BUILDER = new AbstractObjectBuilder<Response>() { @Override public Response get(ElementDescriptor<Response> descriptor, Response recycle, ParserContext context) throws XmlObjectPullParserException { if (recycle != null) { recycle.recycle(); return recycle; } return new Response(); }; @Override public <V> Response update(ElementDescriptor<Response> descriptor, Response object, ElementDescriptor<V> childDescriptor, V child, ParserContext context) throws XmlObjectPullParserException { if (childDescriptor == WebDav.PROPSTAT) { PropStat propStat = (PropStat) child;
if (propStat.getStatusCode() == HttpStatus.NOT_FOUND && context instanceof DavParserContext
dmfs/jdav
src/org/dmfs/dav/rfc6352/filter/PropFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
* The name of the property to match. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, ParamFilter... filters) { this(name, (TextMatch) null, filters); } /** * Creates a filter that matches a property by a specific text value and optionally a list of {@link ParamFilter}s. * * @param name * The name of the property to match. * @param textMatch * The text filter. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, TextMatch textMatch, ParamFilter... filters) { this.name = name; this.isNotDefined = false; this.textMatch = textMatch; this.filters = filters; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc6352/filter/PropFilter.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; * The name of the property to match. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, ParamFilter... filters) { this(name, (TextMatch) null, filters); } /** * Creates a filter that matches a property by a specific text value and optionally a list of {@link ParamFilter}s. * * @param name * The name of the property to match. * @param textMatch * The text filter. * @param filters * Optional list of {@link ParamFilter}s. */ public PropFilter(String name, TextMatch textMatch, ParamFilter... filters) { this.name = name; this.isNotDefined = false; this.textMatch = textMatch; this.filters = filters; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc4791/filter/TextMatch.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // }
import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter;
* Negate the search condition (i.e. return only results that do not match the value). * @param caseInsensitive * Perform case-insensitive matching using the default collation {@link #COLLATION_I_ASCII_CASEMAP}. */ public TextMatch(String value, boolean negate, boolean caseInsensitive) { this(value, negate, caseInsensitive ? COLLATION_I_ASCII_CASEMAP : null); } /** * Create a text-match filter. * * @param value * The filter value. * @param negate * Negate the search condition (i.e. return only results that do not match the value). * @param collation * The collation to use, see <a href="http://tools.ietf.org/html/rfc4790">RFC 4790</a> and <a * href="http://tools.ietf.org/html/rfc4791#section-7.5.1">supported-collation-set</a>. */ public TextMatch(String value, boolean negate, String collation) { this.value = value; this.negate = negate; this.collation = collation; } @Override
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // Path: src/org/dmfs/dav/rfc4791/filter/TextMatch.java import java.io.IOException; import org.dmfs.dav.FilterBase; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.AbstractObjectBuilder; import org.dmfs.xmlobjects.serializer.SerializerContext; import org.dmfs.xmlobjects.serializer.SerializerException; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlAttributeWriter; import org.dmfs.xmlobjects.serializer.XmlObjectSerializer.IXmlChildWriter; * Negate the search condition (i.e. return only results that do not match the value). * @param caseInsensitive * Perform case-insensitive matching using the default collation {@link #COLLATION_I_ASCII_CASEMAP}. */ public TextMatch(String value, boolean negate, boolean caseInsensitive) { this(value, negate, caseInsensitive ? COLLATION_I_ASCII_CASEMAP : null); } /** * Create a text-match filter. * * @param value * The filter value. * @param negate * Negate the search condition (i.e. return only results that do not match the value). * @param collation * The collation to use, see <a href="http://tools.ietf.org/html/rfc4790">RFC 4790</a> and <a * href="http://tools.ietf.org/html/rfc4791#section-7.5.1">supported-collation-set</a>. */ public TextMatch(String value, boolean negate, String collation) { this.value = value; this.negate = negate; this.collation = collation; } @Override
public ElementDescriptor<? extends FilterBase> getElementDescriptor()
dmfs/jdav
src/org/dmfs/dav/rfc6352/filter/CardDavFilter.java
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // // Path: src/org/dmfs/dav/rfc6352/CardDav.java // public final class CardDav // { // /** // * The CardDAV namespace. // */ // public final static String NAMESPACE = "urn:ietf:params:xml:ns:carddav"; // // public final static ElementDescriptor<List<PropFilter>> FILTER = ElementDescriptor.register(QualifiedName.get(NAMESPACE, "filter"), // new ListObjectBuilder<PropFilter>(PropFilter.DESCRIPTOR, 8)); // // /** // * Definition of <code>addressbook-query</code>. This definition is only valid in the context of a {@link WebDavVersioning#REPORT} element. // */ // final static ElementDescriptor<QualifiedName> REPORT_TYPE_ADDRESSBOOK_QUERY = ElementDescriptor.registerWithParents(ReportTypes.ADDRESSBOOK_QUERY, // QualifiedNameObjectBuilder.INSTANCE, WebDavVersioning.REPORT); // // /** // * Definition of the addressbook-query report. // */ // public final static ElementDescriptor<AddressbookQuery> ADDRESSBOOK_QUERY = ElementDescriptor.register(ReportTypes.ADDRESSBOOK_QUERY, // AddressbookQuery.BUILDER); // // /** // * Definition of <code>addressbook-multiget</code>. This definition is only valid in the context of a {@link WebDavVersioning#REPORT} element. // */ // final static ElementDescriptor<QualifiedName> REPORT_TYPE_ADDRESSBOOK_MULTIGET = ElementDescriptor.registerWithParents(ReportTypes.ADDRESSBOOK_MULTIGET, // QualifiedNameObjectBuilder.INSTANCE, WebDavVersioning.REPORT); // // /** // * Definition of the <code>addressbook-multiget</code> report. // */ // public final static ElementDescriptor<AddressbookMultiget> ADDRESSBOOK_MULTIGET = ElementDescriptor.register(ReportTypes.ADDRESSBOOK_MULTIGET, // AddressbookMultiget.BUILDER); // // /** // * Report types defined in <a href="http://tools.ietf.org/html/rfc4791#section-7">RFC 4791, Section 7</a> // */ // public final static class ReportTypes // { // // /** // * {@link QualifiedName} of the addressbook-query element. // */ // public final static QualifiedName ADDRESSBOOK_QUERY = QualifiedName.get(NAMESPACE, "addressbook-query"); // // /** // * {@link QualifiedName} of the addressbook-multiget element. // */ // public final static QualifiedName ADDRESSBOOK_MULTIGET = QualifiedName.get(NAMESPACE, "addressbook-multiget"); // // } // // /** // * addressbook element as defined in <a href="http://tools.ietf.org/html/rfc6352#section-10.1">RFC 6352, section 10.1</a>. // */ // public final static ElementDescriptor<QualifiedName> RESOURCE_TYPE_ADDRESSBOOK = ElementDescriptor.register(ResourceTypes.ADDRESSBOOK, // QualifiedNameObjectBuilder.INSTANCE); // // public final static class ResourceTypes // { // /** // * {@link QualifiedName} of the addressbook element. // */ // public final static QualifiedName ADDRESSBOOK = QualifiedName.get(NAMESPACE, "addressbook"); // // } // // // /** // * No instances allowed. // */ // private CardDav() // { // } // }
import org.dmfs.dav.FilterBase; import org.dmfs.dav.rfc6352.CardDav; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.QualifiedNameObjectBuilder;
/* * Copyright (C) 2014 Marten Gajda <marten@dmfs.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.dav.rfc6352.filter; /** * The base class of all filters in the CardDAV namespace. * * @author Marten Gajda <marten@dmfs.org> */ public abstract class CardDavFilter extends FilterBase { /** * The CalDAV namespace. It's repeated here for the sake of simplicity. */
// Path: src/org/dmfs/dav/FilterBase.java // public abstract class FilterBase // { // /** // * Returns the {@link ElementDescriptor} of this filter. Filters can use this to serialize child elements (which are also filters) in a generic manner. // * // * @return An {@link ElementDescriptor}. // */ // public abstract ElementDescriptor<? extends FilterBase> getElementDescriptor(); // } // // Path: src/org/dmfs/dav/rfc6352/CardDav.java // public final class CardDav // { // /** // * The CardDAV namespace. // */ // public final static String NAMESPACE = "urn:ietf:params:xml:ns:carddav"; // // public final static ElementDescriptor<List<PropFilter>> FILTER = ElementDescriptor.register(QualifiedName.get(NAMESPACE, "filter"), // new ListObjectBuilder<PropFilter>(PropFilter.DESCRIPTOR, 8)); // // /** // * Definition of <code>addressbook-query</code>. This definition is only valid in the context of a {@link WebDavVersioning#REPORT} element. // */ // final static ElementDescriptor<QualifiedName> REPORT_TYPE_ADDRESSBOOK_QUERY = ElementDescriptor.registerWithParents(ReportTypes.ADDRESSBOOK_QUERY, // QualifiedNameObjectBuilder.INSTANCE, WebDavVersioning.REPORT); // // /** // * Definition of the addressbook-query report. // */ // public final static ElementDescriptor<AddressbookQuery> ADDRESSBOOK_QUERY = ElementDescriptor.register(ReportTypes.ADDRESSBOOK_QUERY, // AddressbookQuery.BUILDER); // // /** // * Definition of <code>addressbook-multiget</code>. This definition is only valid in the context of a {@link WebDavVersioning#REPORT} element. // */ // final static ElementDescriptor<QualifiedName> REPORT_TYPE_ADDRESSBOOK_MULTIGET = ElementDescriptor.registerWithParents(ReportTypes.ADDRESSBOOK_MULTIGET, // QualifiedNameObjectBuilder.INSTANCE, WebDavVersioning.REPORT); // // /** // * Definition of the <code>addressbook-multiget</code> report. // */ // public final static ElementDescriptor<AddressbookMultiget> ADDRESSBOOK_MULTIGET = ElementDescriptor.register(ReportTypes.ADDRESSBOOK_MULTIGET, // AddressbookMultiget.BUILDER); // // /** // * Report types defined in <a href="http://tools.ietf.org/html/rfc4791#section-7">RFC 4791, Section 7</a> // */ // public final static class ReportTypes // { // // /** // * {@link QualifiedName} of the addressbook-query element. // */ // public final static QualifiedName ADDRESSBOOK_QUERY = QualifiedName.get(NAMESPACE, "addressbook-query"); // // /** // * {@link QualifiedName} of the addressbook-multiget element. // */ // public final static QualifiedName ADDRESSBOOK_MULTIGET = QualifiedName.get(NAMESPACE, "addressbook-multiget"); // // } // // /** // * addressbook element as defined in <a href="http://tools.ietf.org/html/rfc6352#section-10.1">RFC 6352, section 10.1</a>. // */ // public final static ElementDescriptor<QualifiedName> RESOURCE_TYPE_ADDRESSBOOK = ElementDescriptor.register(ResourceTypes.ADDRESSBOOK, // QualifiedNameObjectBuilder.INSTANCE); // // public final static class ResourceTypes // { // /** // * {@link QualifiedName} of the addressbook element. // */ // public final static QualifiedName ADDRESSBOOK = QualifiedName.get(NAMESPACE, "addressbook"); // // } // // // /** // * No instances allowed. // */ // private CardDav() // { // } // } // Path: src/org/dmfs/dav/rfc6352/filter/CardDavFilter.java import org.dmfs.dav.FilterBase; import org.dmfs.dav.rfc6352.CardDav; import org.dmfs.xmlobjects.ElementDescriptor; import org.dmfs.xmlobjects.QualifiedName; import org.dmfs.xmlobjects.builder.QualifiedNameObjectBuilder; /* * Copyright (C) 2014 Marten Gajda <marten@dmfs.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.dav.rfc6352.filter; /** * The base class of all filters in the CardDAV namespace. * * @author Marten Gajda <marten@dmfs.org> */ public abstract class CardDavFilter extends FilterBase { /** * The CalDAV namespace. It's repeated here for the sake of simplicity. */
public final static String NAMESPACE = CardDav.NAMESPACE;
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // }
import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future;
public ScriptExecutionTask(int taskId, GameScriptingEngine gameScriptingEngine, ScriptExecutor<S> executor, int scriptId, GameScript<S> script, ScriptBindings scriptBindings, ScriptInvocationListener scriptInvocationListener, boolean syncCall) { this.taskId = taskId; this.scriptingEngine = gameScriptingEngine; this.executor = executor; this.scriptId = scriptId; this.script = script; this.scriptBindings = scriptBindings; this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer(
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future; public ScriptExecutionTask(int taskId, GameScriptingEngine gameScriptingEngine, ScriptExecutor<S> executor, int scriptId, GameScript<S> script, ScriptBindings scriptBindings, ScriptInvocationListener scriptInvocationListener, boolean syncCall) { this.taskId = taskId; this.scriptingEngine = gameScriptingEngine; this.executor = executor; this.scriptId = scriptId; this.script = script; this.scriptBindings = scriptBindings; this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer(
new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult));
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // }
import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future;
this.executor = executor; this.scriptId = scriptId; this.script = script; this.scriptBindings = scriptBindings; this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } }
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future; this.executor = executor; this.scriptId = scriptId; this.script = script; this.scriptBindings = scriptBindings; this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } }
} catch (InterruptedException | ScriptSkippedException e) {
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // }
import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future;
this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } } } catch (InterruptedException | ScriptSkippedException e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future; this.scriptInvocationListener = scriptInvocationListener; this.syncCall = syncCall; } @Override public void run() { try { if(scriptInvocationListener != null) { if(scriptInvocationListener instanceof InteractiveScriptListener) { final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } } } catch (InterruptedException | ScriptSkippedException e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications
.offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId()));
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // }
import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future;
final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } } } catch (InterruptedException | ScriptSkippedException e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId())); } else { scriptInvocationListener.onScriptSkipped(script.getId()); } } } catch (Exception e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future; final ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener(); invokeOnScriptBegin(actualListener); } else { invokeOnScriptBegin(scriptInvocationListener); } } ScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings, scriptInvocationListener != null); if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications.offer( new ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult)); } else { scriptInvocationListener.onScriptSuccess(script.getId(), executionResult); } } } catch (InterruptedException | ScriptSkippedException e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId())); } else { scriptInvocationListener.onScriptSkipped(script.getId()); } } } catch (Exception e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications
.offer(new ScriptExceptionNotification(scriptInvocationListener, script.getId(), e));
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // }
import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future;
if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId())); } else { scriptInvocationListener.onScriptSkipped(script.getId()); } } } catch (Exception e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptExceptionNotification(scriptInvocationListener, script.getId(), e)); } else { scriptInvocationListener.onScriptException(script.getId(), e); } } else { e.printStackTrace(); } } // Clear interrupted bit Thread.interrupted(); completed.set(true); } private void invokeOnScriptBegin(ScriptInvocationListener listener) throws InterruptedException { if(listener == null) { return; } if(listener.callOnGameThread() && !syncCall) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java // public class ScriptBeginNotification implements ScriptNotification { // private final AtomicBoolean processed = new AtomicBoolean(false); // private final ScriptInvocationListener invocationListener; // private final int scriptId; // // public ScriptBeginNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // @Override // public void process() { // invocationListener.onScriptBegin(scriptId); // processed.set(true); // // synchronized(this) { // this.notifyAll(); // } // } // // public boolean isProcessed() { // return processed.get(); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptExceptionNotification.java // public class ScriptExceptionNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final Exception exception; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptExceptionNotification(ScriptInvocationListener invocationListener, int scriptId, Exception exception) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.exception = exception; // } // // @Override // public void process() { // try { // invocationListener.onScriptException(scriptId, exception); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSkippedNotification.java // public class ScriptSkippedNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSkippedNotification(ScriptInvocationListener invocationListener, int scriptId) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // } // // @Override // public void process() { // try { // invocationListener.onScriptSkipped(scriptId); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java // public class ScriptSuccessNotification implements ScriptNotification { // private final ScriptInvocationListener invocationListener; // private final int scriptId; // private final ScriptExecutionResult executionResult; // private final AtomicBoolean notified = new AtomicBoolean(false); // // public ScriptSuccessNotification(ScriptInvocationListener invocationListener, int scriptId, // ScriptExecutionResult executionResult) { // this.invocationListener = invocationListener; // this.scriptId = scriptId; // this.executionResult = executionResult; // } // // @Override // public void process() { // try { // invocationListener.onScriptSuccess(scriptId, executionResult); // } finally { // notified.set(true); // } // // synchronized(this) { // notifyAll(); // } // } // // public void waitForNotification() { // while(!notified.get()) { // synchronized(this) { // try { // wait(); // } catch (InterruptedException e) {} // } // } // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionTask.java import java.util.concurrent.atomic.AtomicBoolean; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.mini2Dx.miniscript.core.notification.ScriptBeginNotification; import org.mini2Dx.miniscript.core.notification.ScriptExceptionNotification; import org.mini2Dx.miniscript.core.notification.ScriptSkippedNotification; import org.mini2Dx.miniscript.core.notification.ScriptSuccessNotification; import java.util.concurrent.Future; if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId())); } else { scriptInvocationListener.onScriptSkipped(script.getId()); } } } catch (Exception e) { if (scriptInvocationListener != null) { if (scriptInvocationListener.callOnGameThread()) { scriptingEngine.scriptNotifications .offer(new ScriptExceptionNotification(scriptInvocationListener, script.getId(), e)); } else { scriptInvocationListener.onScriptException(script.getId(), e); } } else { e.printStackTrace(); } } // Clear interrupted bit Thread.interrupted(); completed.set(true); } private void invokeOnScriptBegin(ScriptInvocationListener listener) throws InterruptedException { if(listener == null) { return; } if(listener.callOnGameThread() && !syncCall) {
final ScriptBeginNotification beginNotification = new ScriptBeginNotification(listener, scriptId);
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/ImmediateGameFutureTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // }
import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ImmediateGameFuture} */ public class ImmediateGameFutureTest { @Test() public void testNoArgConstructor() {
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameScriptingEngine.java // public class DummyGameScriptingEngine extends GameScriptingEngine { // // @Override // protected ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider, int poolSize, boolean sandboxing) { // return new DummyScriptExecutorPool(this, poolSize); // } // // @Override // public boolean isSandboxingSupported() { // return false; // } // // @Override // public boolean isEmbeddedSynchronousScriptSupported() { // return true; // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/ImmediateGameFutureTest.java import org.junit.Assert; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameScriptingEngine; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Unit tests for {@link ImmediateGameFuture} */ public class ImmediateGameFutureTest { @Test() public void testNoArgConstructor() {
GameScriptingEngine dummyEngine = new DummyGameScriptingEngine();
mini2Dx/miniscript
python/src/main/java/org/mini2Dx/miniscript/python/PythonScriptExecutor.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.python.core.*; import org.python.util.InteractiveInterpreter;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.python; /** * An implementation of {@link ScriptExecutor} for Python-based scripts */ public class PythonScriptExecutor implements ScriptExecutor<PyCode> { private final PythonScriptExecutorPool executorPool; private final InteractiveInterpreter pythonInterpreter; public PythonScriptExecutor(PythonScriptExecutorPool executorPool) { this.executorPool = executorPool; pythonInterpreter = new InteractiveInterpreter(); pythonInterpreter.setErr(System.err); pythonInterpreter.setOut(System.out); } @Override public GameScript<PyCode> compile(String script) { return new GlobalGameScript<PyCode>(pythonInterpreter.compile(script)); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<PyCode> script, ScriptBindings bindings, boolean returnResult) throws Exception { final PyCode pythonScript = script.getScript(); final PythonEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { pythonInterpreter.set(variableName, bindings.get(variableName)); } pythonInterpreter.set(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); pythonInterpreter.set(ScriptBindings.SCRIPT_ID_VAR, scriptId); pythonInterpreter.set(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); try { pythonInterpreter.exec(pythonScript); } catch (PyException e) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: python/src/main/java/org/mini2Dx/miniscript/python/PythonScriptExecutor.java import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; import org.python.core.*; import org.python.util.InteractiveInterpreter; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.python; /** * An implementation of {@link ScriptExecutor} for Python-based scripts */ public class PythonScriptExecutor implements ScriptExecutor<PyCode> { private final PythonScriptExecutorPool executorPool; private final InteractiveInterpreter pythonInterpreter; public PythonScriptExecutor(PythonScriptExecutorPool executorPool) { this.executorPool = executorPool; pythonInterpreter = new InteractiveInterpreter(); pythonInterpreter.setErr(System.err); pythonInterpreter.setOut(System.out); } @Override public GameScript<PyCode> compile(String script) { return new GlobalGameScript<PyCode>(pythonInterpreter.compile(script)); } @Override public ScriptExecutionResult execute(int scriptId, GameScript<PyCode> script, ScriptBindings bindings, boolean returnResult) throws Exception { final PyCode pythonScript = script.getScript(); final PythonEmbeddedScriptInvoker embeddedScriptInvoker = executorPool.getEmbeddedScriptInvokerPool().allocate(); embeddedScriptInvoker.setScriptBindings(bindings); embeddedScriptInvoker.setScriptExecutor(this); embeddedScriptInvoker.setParentScriptId(scriptId); for (String variableName : bindings.keySet()) { pythonInterpreter.set(variableName, bindings.get(variableName)); } pythonInterpreter.set(ScriptBindings.SCRIPT_PARENT_ID_VAR, -1); pythonInterpreter.set(ScriptBindings.SCRIPT_ID_VAR, scriptId); pythonInterpreter.set(ScriptBindings.SCRIPT_INVOKE_VAR, embeddedScriptInvoker); try { pythonInterpreter.exec(pythonScript); } catch (PyException e) {
if(e.getCause() instanceof ScriptSkippedException) {
mini2Dx/miniscript
gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/compiler/CompilerConfig.java
// Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/CompilerInputFile.java // public class CompilerInputFile { // private final File inputScriptFile; // private final String inputScriptFilename; // private final String inputScriptFileSuffix; // private final String inputScriptFilenameWithoutSuffix; // private final String inputScriptRelativeFilename; // private final String outputClassName; // // public CompilerInputFile(File scriptsRootDir, File scriptFile) { // super(); // this.inputScriptFile = scriptFile; // this.inputScriptFilename = inputScriptFile.getName(); // this.inputScriptFileSuffix = inputScriptFilename.substring(inputScriptFilename.lastIndexOf('.')).toLowerCase(); // this.inputScriptFilenameWithoutSuffix = inputScriptFile.getName().substring( 0, inputScriptFile.getName().lastIndexOf('.')); // final String inputScriptRelativeFilename = inputScriptFile.getAbsolutePath().replace(scriptsRootDir.getAbsolutePath(), ""); // // if(inputScriptRelativeFilename.startsWith("/") || inputScriptRelativeFilename.startsWith("\\")) { // this.inputScriptRelativeFilename = inputScriptRelativeFilename.substring(1); // } else { // this.inputScriptRelativeFilename = inputScriptRelativeFilename; // } // // this.outputClassName = inputScriptFilenameWithoutSuffix.replace('-', '_'); // } // // public File getInputScriptFile() { // return inputScriptFile; // } // // public String getInputScriptFilename() { // return inputScriptFilename; // } // // public String getInputScriptFileSuffix() { // return inputScriptFileSuffix; // } // // public String getInputScriptFilenameWithoutSuffix() { // return inputScriptFilenameWithoutSuffix; // } // // public String getInputScriptRelativeFilename() { // return inputScriptRelativeFilename; // } // // public String getOutputClassName() { // return outputClassName; // } // // public String getOutputPackageName(String rootScriptPackage) { // if(inputScriptRelativeFilename.indexOf('/') > 0 || inputScriptRelativeFilename.indexOf('\\') > 0) { // final String initialResult = rootScriptPackage + '.' + inputScriptRelativeFilename. // substring(0, inputScriptRelativeFilename.indexOf('/') > 0 ? // inputScriptRelativeFilename.lastIndexOf('/') : // inputScriptRelativeFilename.lastIndexOf('\\')). // replace('/', '.'). // replace('\\', '.'). // replace('-', '_'); // // final StringBuilder result = new StringBuilder(); // result.append(initialResult.charAt(0)); // for(int i = 1; i < initialResult.length(); i++) { // if(initialResult.charAt(i - 1) != '.') { // result.append(initialResult.charAt(i)); // continue; // } // if(Character.isJavaIdentifierStart(initialResult.charAt(i))) { // result.append(initialResult.charAt(i)); // continue; // } // result.append('_'); // result.append(initialResult.charAt(i)); // } // return result.toString(); // } // return rootScriptPackage; // } // }
import org.mini2Dx.miniscript.gradle.CompilerInputFile; import java.io.File;
/** * The MIT License (MIT) * * Copyright (c) 2018 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.gradle.compiler; public class CompilerConfig { private final File rootOutputDir; private final String outputRootPackage; private final String outputRootPackageAsPath; private final File outputRootDirectory;
// Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/CompilerInputFile.java // public class CompilerInputFile { // private final File inputScriptFile; // private final String inputScriptFilename; // private final String inputScriptFileSuffix; // private final String inputScriptFilenameWithoutSuffix; // private final String inputScriptRelativeFilename; // private final String outputClassName; // // public CompilerInputFile(File scriptsRootDir, File scriptFile) { // super(); // this.inputScriptFile = scriptFile; // this.inputScriptFilename = inputScriptFile.getName(); // this.inputScriptFileSuffix = inputScriptFilename.substring(inputScriptFilename.lastIndexOf('.')).toLowerCase(); // this.inputScriptFilenameWithoutSuffix = inputScriptFile.getName().substring( 0, inputScriptFile.getName().lastIndexOf('.')); // final String inputScriptRelativeFilename = inputScriptFile.getAbsolutePath().replace(scriptsRootDir.getAbsolutePath(), ""); // // if(inputScriptRelativeFilename.startsWith("/") || inputScriptRelativeFilename.startsWith("\\")) { // this.inputScriptRelativeFilename = inputScriptRelativeFilename.substring(1); // } else { // this.inputScriptRelativeFilename = inputScriptRelativeFilename; // } // // this.outputClassName = inputScriptFilenameWithoutSuffix.replace('-', '_'); // } // // public File getInputScriptFile() { // return inputScriptFile; // } // // public String getInputScriptFilename() { // return inputScriptFilename; // } // // public String getInputScriptFileSuffix() { // return inputScriptFileSuffix; // } // // public String getInputScriptFilenameWithoutSuffix() { // return inputScriptFilenameWithoutSuffix; // } // // public String getInputScriptRelativeFilename() { // return inputScriptRelativeFilename; // } // // public String getOutputClassName() { // return outputClassName; // } // // public String getOutputPackageName(String rootScriptPackage) { // if(inputScriptRelativeFilename.indexOf('/') > 0 || inputScriptRelativeFilename.indexOf('\\') > 0) { // final String initialResult = rootScriptPackage + '.' + inputScriptRelativeFilename. // substring(0, inputScriptRelativeFilename.indexOf('/') > 0 ? // inputScriptRelativeFilename.lastIndexOf('/') : // inputScriptRelativeFilename.lastIndexOf('\\')). // replace('/', '.'). // replace('\\', '.'). // replace('-', '_'); // // final StringBuilder result = new StringBuilder(); // result.append(initialResult.charAt(0)); // for(int i = 1; i < initialResult.length(); i++) { // if(initialResult.charAt(i - 1) != '.') { // result.append(initialResult.charAt(i)); // continue; // } // if(Character.isJavaIdentifierStart(initialResult.charAt(i))) { // result.append(initialResult.charAt(i)); // continue; // } // result.append('_'); // result.append(initialResult.charAt(i)); // } // return result.toString(); // } // return rootScriptPackage; // } // } // Path: gradle-plugin/src/main/java/org/mini2Dx/miniscript/gradle/compiler/CompilerConfig.java import org.mini2Dx.miniscript.gradle.CompilerInputFile; import java.io.File; /** * The MIT License (MIT) * * Copyright (c) 2018 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.gradle.compiler; public class CompilerConfig { private final File rootOutputDir; private final String outputRootPackage; private final String outputRootPackageAsPath; private final File outputRootDirectory;
private CompilerInputFile inputScriptFile;
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionResult.java // public class ScriptExecutionResult extends ScriptBindings { // // public ScriptExecutionResult(Map<String, Object> results) { // if(results == null) { // return; // } // super.putAll(results); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationListener.java // public interface ScriptInvocationListener { // /** // * Called just before a script begins execution. Note: If callOnGameThread() is true, // * the script will not begin until this callback is processed on the game thread // * @param scriptId The script id // */ // public default void onScriptBegin(int scriptId) { // // } // // /** // * Called when a script is cancelled while in the invoke queue. // * // * @param scriptId The script id // */ // public default void onScriptCancelled(int scriptId) { // } // // /** // * Called when a script successfully completes // * // * @param scriptId // * The script id // * @param executionResult // * The variable bindings after execution // */ // public void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult); // // /** // * Called when a script is skipped during execution // * // * @param scriptId // * The script id // */ // public void onScriptSkipped(int scriptId); // // /** // * Called when an exception occurs during script execution // * // * @param scriptId // * The script id // * @param e // * The exception that occurred // */ // public void onScriptException(int scriptId, Exception e); // // /** // * Returns if this {@link ScriptInvocationListener} should be notified on // * the game thread // * // * @return False if this should be notified on the // * {@link GameScriptingEngine} thread pool // */ // public boolean callOnGameThread(); // }
import org.mini2Dx.miniscript.core.ScriptExecutionResult; import org.mini2Dx.miniscript.core.ScriptInvocationListener; import java.util.concurrent.atomic.AtomicBoolean;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.notification; /** * */ public class ScriptSuccessNotification implements ScriptNotification { private final ScriptInvocationListener invocationListener; private final int scriptId;
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptExecutionResult.java // public class ScriptExecutionResult extends ScriptBindings { // // public ScriptExecutionResult(Map<String, Object> results) { // if(results == null) { // return; // } // super.putAll(results); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationListener.java // public interface ScriptInvocationListener { // /** // * Called just before a script begins execution. Note: If callOnGameThread() is true, // * the script will not begin until this callback is processed on the game thread // * @param scriptId The script id // */ // public default void onScriptBegin(int scriptId) { // // } // // /** // * Called when a script is cancelled while in the invoke queue. // * // * @param scriptId The script id // */ // public default void onScriptCancelled(int scriptId) { // } // // /** // * Called when a script successfully completes // * // * @param scriptId // * The script id // * @param executionResult // * The variable bindings after execution // */ // public void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult); // // /** // * Called when a script is skipped during execution // * // * @param scriptId // * The script id // */ // public void onScriptSkipped(int scriptId); // // /** // * Called when an exception occurs during script execution // * // * @param scriptId // * The script id // * @param e // * The exception that occurred // */ // public void onScriptException(int scriptId, Exception e); // // /** // * Returns if this {@link ScriptInvocationListener} should be notified on // * the game thread // * // * @return False if this should be notified on the // * {@link GameScriptingEngine} thread pool // */ // public boolean callOnGameThread(); // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptSuccessNotification.java import org.mini2Dx.miniscript.core.ScriptExecutionResult; import org.mini2Dx.miniscript.core.ScriptInvocationListener; import java.util.concurrent.atomic.AtomicBoolean; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.notification; /** * */ public class ScriptSuccessNotification implements ScriptNotification { private final ScriptInvocationListener invocationListener; private final int scriptId;
private final ScriptExecutionResult executionResult;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // }
import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings;
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings;
protected DummyGameFuture gameFuture;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // }
import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture;
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture;
protected DummyJavaObject javaObject;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // }
import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected DummyJavaObject javaObject; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted;
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected DummyJavaObject javaObject; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted;
protected AtomicReference<ScriptResult> scriptResult;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // }
import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected DummyJavaObject javaObject; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted; protected AtomicReference<ScriptResult> scriptResult; @Before public void setUp() { scriptingEngine = createScriptingEngineWithSandboxing(); javaObject = new DummyJavaObject(); gameFuture = new DummyGameFuture(scriptingEngine); scriptExecuted = new AtomicBoolean(false); scriptResult = new AtomicReference<ScriptResult>(ScriptResult.NOT_EXECUTED); scriptBindings = new ScriptBindings(); scriptBindings.put("stringValue", "hello"); scriptBindings.put("booleanValue", false); scriptBindings.put("intValue", 7); scriptBindings.put("future", gameFuture); scriptBindings.put("jObject", javaObject); } @After public void teardown() { scriptingEngine.dispose(); } @Test
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyJavaObject.java // public class DummyJavaObject { // private int value; // // public int getValue() { // return value; // } // // public void setValue(int value) { // this.value = value; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/InsufficientCompilersException.java // public class InsufficientCompilersException extends Exception { // private static final long serialVersionUID = 2947579725300422095L; // // public InsufficientCompilersException() { // super("There were insufficient compilers available to compile the provided script"); // } // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/SandboxedGameScriptingEngineTest.java import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.DummyJavaObject; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Assert; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations that support sandboxing */ public abstract class SandboxedGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected DummyJavaObject javaObject; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted; protected AtomicReference<ScriptResult> scriptResult; @Before public void setUp() { scriptingEngine = createScriptingEngineWithSandboxing(); javaObject = new DummyJavaObject(); gameFuture = new DummyGameFuture(scriptingEngine); scriptExecuted = new AtomicBoolean(false); scriptResult = new AtomicReference<ScriptResult>(ScriptResult.NOT_EXECUTED); scriptBindings = new ScriptBindings(); scriptBindings.put("stringValue", "hello"); scriptBindings.put("booleanValue", false); scriptBindings.put("intValue", 7); scriptBindings.put("future", gameFuture); scriptBindings.put("jObject", javaObject); } @After public void teardown() { scriptingEngine.dispose(); } @Test
public void testSandboxScript() throws InsufficientCompilersException, IOException {
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationListener.java // public interface ScriptInvocationListener { // /** // * Called just before a script begins execution. Note: If callOnGameThread() is true, // * the script will not begin until this callback is processed on the game thread // * @param scriptId The script id // */ // public default void onScriptBegin(int scriptId) { // // } // // /** // * Called when a script is cancelled while in the invoke queue. // * // * @param scriptId The script id // */ // public default void onScriptCancelled(int scriptId) { // } // // /** // * Called when a script successfully completes // * // * @param scriptId // * The script id // * @param executionResult // * The variable bindings after execution // */ // public void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult); // // /** // * Called when a script is skipped during execution // * // * @param scriptId // * The script id // */ // public void onScriptSkipped(int scriptId); // // /** // * Called when an exception occurs during script execution // * // * @param scriptId // * The script id // * @param e // * The exception that occurred // */ // public void onScriptException(int scriptId, Exception e); // // /** // * Returns if this {@link ScriptInvocationListener} should be notified on // * the game thread // * // * @return False if this should be notified on the // * {@link GameScriptingEngine} thread pool // */ // public boolean callOnGameThread(); // }
import org.mini2Dx.miniscript.core.ScriptInvocationListener; import java.util.concurrent.atomic.AtomicBoolean;
/** * Copyright 2021 Viridian Software Ltd. */ package org.mini2Dx.miniscript.core.notification; public class ScriptBeginNotification implements ScriptNotification { private final AtomicBoolean processed = new AtomicBoolean(false);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/ScriptInvocationListener.java // public interface ScriptInvocationListener { // /** // * Called just before a script begins execution. Note: If callOnGameThread() is true, // * the script will not begin until this callback is processed on the game thread // * @param scriptId The script id // */ // public default void onScriptBegin(int scriptId) { // // } // // /** // * Called when a script is cancelled while in the invoke queue. // * // * @param scriptId The script id // */ // public default void onScriptCancelled(int scriptId) { // } // // /** // * Called when a script successfully completes // * // * @param scriptId // * The script id // * @param executionResult // * The variable bindings after execution // */ // public void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult); // // /** // * Called when a script is skipped during execution // * // * @param scriptId // * The script id // */ // public void onScriptSkipped(int scriptId); // // /** // * Called when an exception occurs during script execution // * // * @param scriptId // * The script id // * @param e // * The exception that occurred // */ // public void onScriptException(int scriptId, Exception e); // // /** // * Returns if this {@link ScriptInvocationListener} should be notified on // * the game thread // * // * @return False if this should be notified on the // * {@link GameScriptingEngine} thread pool // */ // public boolean callOnGameThread(); // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/notification/ScriptBeginNotification.java import org.mini2Dx.miniscript.core.ScriptInvocationListener; import java.util.concurrent.atomic.AtomicBoolean; /** * Copyright 2021 Viridian Software Ltd. */ package org.mini2Dx.miniscript.core.notification; public class ScriptBeginNotification implements ScriptNotification { private final AtomicBoolean processed = new AtomicBoolean(false);
private final ScriptInvocationListener invocationListener;
mini2Dx/miniscript
lua/src/main/java/org/mini2Dx/miniscript/lua/LuaEmbeddedScriptInvoker.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.luaj.vm2.LuaValue; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.NoSuchScriptException; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException;
/** * The MIT License (MIT) * * Copyright (c) 2020 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; public class LuaEmbeddedScriptInvoker extends EmbeddedScriptInvoker { private final LuaScriptExecutorPool luaScriptExecutorPool; private LuaScriptExecutor scriptExecutor; public LuaEmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine, LuaScriptExecutorPool luaScriptExecutorPool) { super(gameScriptingEngine); this.luaScriptExecutorPool = luaScriptExecutorPool; } @Override public void invokeSync(int scriptId) { final GameScript<LuaValue> script = luaScriptExecutorPool.getScript(scriptId); if(script == null) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: lua/src/main/java/org/mini2Dx/miniscript/lua/LuaEmbeddedScriptInvoker.java import org.luaj.vm2.LuaValue; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.NoSuchScriptException; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; /** * The MIT License (MIT) * * Copyright (c) 2020 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; public class LuaEmbeddedScriptInvoker extends EmbeddedScriptInvoker { private final LuaScriptExecutorPool luaScriptExecutorPool; private LuaScriptExecutor scriptExecutor; public LuaEmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine, LuaScriptExecutorPool luaScriptExecutorPool) { super(gameScriptingEngine); this.luaScriptExecutorPool = luaScriptExecutorPool; } @Override public void invokeSync(int scriptId) { final GameScript<LuaValue> script = luaScriptExecutorPool.getScript(scriptId); if(script == null) {
throw new NoSuchScriptException(scriptId);
mini2Dx/miniscript
lua/src/main/java/org/mini2Dx/miniscript/lua/LuaEmbeddedScriptInvoker.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // }
import org.luaj.vm2.LuaValue; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.NoSuchScriptException; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException;
/** * The MIT License (MIT) * * Copyright (c) 2020 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; public class LuaEmbeddedScriptInvoker extends EmbeddedScriptInvoker { private final LuaScriptExecutorPool luaScriptExecutorPool; private LuaScriptExecutor scriptExecutor; public LuaEmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine, LuaScriptExecutorPool luaScriptExecutorPool) { super(gameScriptingEngine); this.luaScriptExecutorPool = luaScriptExecutorPool; } @Override public void invokeSync(int scriptId) { final GameScript<LuaValue> script = luaScriptExecutorPool.getScript(scriptId); if(script == null) { throw new NoSuchScriptException(scriptId); } try { scriptExecutor.executeEmbedded(parentScriptId, scriptId, script, this, scriptBindings); } catch (Exception e) {
// Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/NoSuchScriptException.java // public class NoSuchScriptException extends RuntimeException { // // public NoSuchScriptException(int scriptId) { // super("No script with id " + scriptId + " exists"); // } // // public NoSuchScriptException(String filepath) { // super("No script " + filepath + " exists"); // } // } // // Path: core/src/main/java/org/mini2Dx/miniscript/core/exception/ScriptSkippedException.java // public class ScriptSkippedException extends RuntimeException { // private static final long serialVersionUID = -7901574884568506426L; // // } // Path: lua/src/main/java/org/mini2Dx/miniscript/lua/LuaEmbeddedScriptInvoker.java import org.luaj.vm2.LuaValue; import org.mini2Dx.miniscript.core.*; import org.mini2Dx.miniscript.core.exception.NoSuchScriptException; import org.mini2Dx.miniscript.core.exception.ScriptSkippedException; /** * The MIT License (MIT) * * Copyright (c) 2020 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.lua; public class LuaEmbeddedScriptInvoker extends EmbeddedScriptInvoker { private final LuaScriptExecutorPool luaScriptExecutorPool; private LuaScriptExecutor scriptExecutor; public LuaEmbeddedScriptInvoker(GameScriptingEngine gameScriptingEngine, LuaScriptExecutorPool luaScriptExecutorPool) { super(gameScriptingEngine); this.luaScriptExecutorPool = luaScriptExecutorPool; } @Override public void invokeSync(int scriptId) { final GameScript<LuaValue> script = luaScriptExecutorPool.getScript(scriptId); if(script == null) { throw new NoSuchScriptException(scriptId); } try { scriptExecutor.executeEmbedded(parentScriptId, scriptId, script, this, scriptBindings); } catch (Exception e) {
if(e instanceof ScriptSkippedException || e.getCause() instanceof ScriptSkippedException) {
mini2Dx/miniscript
core/src/main/java/org/mini2Dx/miniscript/core/threadpool/ScheduledTaskFuture.java
// Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ReadWritePriorityQueue.java // public class ReadWritePriorityQueue<E> extends AbstractConcurrentBlockingQueue<E> { // // public ReadWritePriorityQueue() { // this(Integer.MAX_VALUE); // } // // public ReadWritePriorityQueue(int maxCapacity) { // super(maxCapacity, new PriorityQueue<>()); // } // }
import org.mini2Dx.miniscript.core.util.ReadWritePriorityQueue; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference;
/** * The MIT License (MIT) * * Copyright (c) 2021 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.threadpool; public class ScheduledTaskFuture<T extends Object> implements ScheduledFuture<T> { private final Object monitor = new Object(); private final AtomicBoolean done = new AtomicBoolean(false); private final AtomicBoolean cancelled = new AtomicBoolean(false); private final AtomicReference<Thread> executingThread = new AtomicReference<>(null);
// Path: core/src/main/java/org/mini2Dx/miniscript/core/util/ReadWritePriorityQueue.java // public class ReadWritePriorityQueue<E> extends AbstractConcurrentBlockingQueue<E> { // // public ReadWritePriorityQueue() { // this(Integer.MAX_VALUE); // } // // public ReadWritePriorityQueue(int maxCapacity) { // super(maxCapacity, new PriorityQueue<>()); // } // } // Path: core/src/main/java/org/mini2Dx/miniscript/core/threadpool/ScheduledTaskFuture.java import org.mini2Dx.miniscript.core.util.ReadWritePriorityQueue; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * The MIT License (MIT) * * Copyright (c) 2021 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.threadpool; public class ScheduledTaskFuture<T extends Object> implements ScheduledFuture<T> { private final Object monitor = new Object(); private final AtomicBoolean done = new AtomicBoolean(false); private final AtomicBoolean cancelled = new AtomicBoolean(false); private final AtomicReference<Thread> executingThread = new AtomicReference<>(null);
private final ReadWritePriorityQueue<ScheduledTask> scheduledTaskQueue;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/AbstractGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // }
import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.junit.After;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations */ public abstract class AbstractGameScriptingEngineTest { protected ScriptBindings scriptBindings;
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/AbstractGameScriptingEngineTest.java import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations */ public abstract class AbstractGameScriptingEngineTest { protected ScriptBindings scriptBindings;
protected DummyGameFuture gameFuture;
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/AbstractGameScriptingEngineTest.java
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // }
import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.junit.After;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations */ public abstract class AbstractGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted;
// Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyGameFuture.java // public class DummyGameFuture extends GameFuture { // private boolean updated = false; // private boolean futureSkipped = false; // private boolean scriptSkipped = false; // private boolean futureCompleted = false; // private boolean waitOccurred = false; // private int updateCount = 0; // // public DummyGameFuture(GameScriptingEngine gameScriptingEngine) { // super(gameScriptingEngine); // } // // @Override // protected boolean update(float delta) { // updated = true; // updateCount++; // return futureCompleted; // } // // @Override // protected void onFutureSkipped() { // futureSkipped = true; // } // // @Override // protected void onScriptSkipped() { // scriptSkipped = true; // } // // @Override // public void waitForCompletion() throws ScriptSkippedException { // waitOccurred = true; // super.waitForCompletion(); // } // // public boolean isFutureCompleted() { // return futureCompleted; // } // // public void setFutureCompleted(boolean futureCompleted) { // this.futureCompleted = futureCompleted; // } // // public boolean isUpdated() { // return updated; // } // // public boolean isFutureSkippedCalled() { // return futureSkipped; // } // // public boolean isScriptSkippedCalled() { // return scriptSkipped; // } // // public boolean waitOccurred() { // return waitOccurred; // } // // public int getUpdateCount() { // return updateCount; // } // } // // Path: core/src/test/java/org/mini2Dx/miniscript/core/dummy/ScriptResult.java // public enum ScriptResult { // NOT_EXECUTED, // INCORRECT_SCRIPT_ID, // INCORRECT_VARIABLES, // CANCELLED, // SUCCESS, // SKIPPED, // EXCEPTION // } // Path: core/src/test/java/org/mini2Dx/miniscript/core/AbstractGameScriptingEngineTest.java import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mini2Dx.miniscript.core.dummy.DummyGameFuture; import org.mini2Dx.miniscript.core.dummy.ScriptResult; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; /** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core; /** * Base UAT class for {@link GameScriptingEngine} implementations */ public abstract class AbstractGameScriptingEngineTest { protected ScriptBindings scriptBindings; protected DummyGameFuture gameFuture; protected GameScriptingEngine scriptingEngine; protected AtomicBoolean scriptExecuted;
protected AtomicReference<ScriptResult> scriptResult;