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
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java // @Component(modules = {AppModule.class}) // public interface AppComponent { // void inject(Application application); // // @Named(AppModule.CACHE_MANAGER) // CacheManager getCacheManager(); // // @Named(AppModule.RESOURCES) // Resources getResources(); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // }
import android.content.Context; import com.bugsnag.android.Bugsnag; import com.facebook.stetho.Stetho; import com.orm.SugarApp; import io.dwak.holohackernews.app.dagger.component.AppComponent; import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent; import io.dwak.holohackernews.app.dagger.module.AppModule; import io.dwak.holohackernews.app.preferences.LocalDataManager;
package io.dwak.holohackernews.app; public class HackerNewsApplication extends SugarApp { private static boolean mDebug = BuildConfig.DEBUG; private static HackerNewsApplication sInstance; private Context mContext; private static AppComponent sAppComponent;
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java // @Component(modules = {AppModule.class}) // public interface AppComponent { // void inject(Application application); // // @Named(AppModule.CACHE_MANAGER) // CacheManager getCacheManager(); // // @Named(AppModule.RESOURCES) // Resources getResources(); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java import android.content.Context; import com.bugsnag.android.Bugsnag; import com.facebook.stetho.Stetho; import com.orm.SugarApp; import io.dwak.holohackernews.app.dagger.component.AppComponent; import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent; import io.dwak.holohackernews.app.dagger.module.AppModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; package io.dwak.holohackernews.app; public class HackerNewsApplication extends SugarApp { private static boolean mDebug = BuildConfig.DEBUG; private static HackerNewsApplication sInstance; private Context mContext; private static AppComponent sAppComponent;
private static AppModule sAppModule;
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java // @Component(modules = {AppModule.class}) // public interface AppComponent { // void inject(Application application); // // @Named(AppModule.CACHE_MANAGER) // CacheManager getCacheManager(); // // @Named(AppModule.RESOURCES) // Resources getResources(); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // }
import android.content.Context; import com.bugsnag.android.Bugsnag; import com.facebook.stetho.Stetho; import com.orm.SugarApp; import io.dwak.holohackernews.app.dagger.component.AppComponent; import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent; import io.dwak.holohackernews.app.dagger.module.AppModule; import io.dwak.holohackernews.app.preferences.LocalDataManager;
package io.dwak.holohackernews.app; public class HackerNewsApplication extends SugarApp { private static boolean mDebug = BuildConfig.DEBUG; private static HackerNewsApplication sInstance; private Context mContext; private static AppComponent sAppComponent; private static AppModule sAppModule; @Override public void onCreate() { super.onCreate(); if (sInstance == null) { sInstance = this; } if("release".equals(BuildConfig.BUILD_TYPE)){ Bugsnag.init(this); } mContext = getApplicationContext(); Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp( Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector( Stetho.defaultInspectorModulesProvider(this)) .build()); sAppModule = new AppModule(this); sAppComponent = DaggerAppComponent.builder() .appModule(sAppModule) .build(); sAppComponent.inject(this);
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java // @Component(modules = {AppModule.class}) // public interface AppComponent { // void inject(Application application); // // @Named(AppModule.CACHE_MANAGER) // CacheManager getCacheManager(); // // @Named(AppModule.RESOURCES) // Resources getResources(); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java import android.content.Context; import com.bugsnag.android.Bugsnag; import com.facebook.stetho.Stetho; import com.orm.SugarApp; import io.dwak.holohackernews.app.dagger.component.AppComponent; import io.dwak.holohackernews.app.dagger.component.DaggerAppComponent; import io.dwak.holohackernews.app.dagger.module.AppModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; package io.dwak.holohackernews.app; public class HackerNewsApplication extends SugarApp { private static boolean mDebug = BuildConfig.DEBUG; private static HackerNewsApplication sInstance; private Context mContext; private static AppComponent sAppComponent; private static AppModule sAppModule; @Override public void onCreate() { super.onCreate(); if (sInstance == null) { sInstance = this; } if("release".equals(BuildConfig.BUILD_TYPE)){ Bugsnag.init(this); } mContext = getApplicationContext(); Stetho.initialize( Stetho.newInitializerBuilder(this) .enableDumpapp( Stetho.defaultDumperPluginsProvider(this)) .enableWebKitInspector( Stetho.defaultInspectorModulesProvider(this)) .build()); sAppModule = new AppModule(this); sAppComponent = DaggerAppComponent.builder() .appModule(sAppModule) .build(); sAppComponent.inject(this);
LocalDataManager.initialize(mContext);
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // }
import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient;
package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient; package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton
HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // }
import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient;
package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient; package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
@Named("loganSquare") LoganSquareConvertor loganSquareConvertor,
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // }
import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient;
package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setConverter(loganSquareConvertor) .setLogLevel(logLevel) .setClient(okClient) .setEndpoint("https://whispering-fortress-7282.herokuapp.com/") .build() .create(HackerNewsService.class); } @Provides @Singleton
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient; package io.dwak.holohackernews.app.dagger.module; @Module(includes = {AppModule.class, OkClientModule.class}) public class NetworkServiceModule { @Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setConverter(loganSquareConvertor) .setLogLevel(logLevel) .setClient(okClient) .setEndpoint("https://whispering-fortress-7282.herokuapp.com/") .build() .create(HackerNewsService.class); } @Provides @Singleton
LoginService providesLoginService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // }
import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient;
@Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setConverter(loganSquareConvertor) .setLogLevel(logLevel) .setClient(okClient) .setEndpoint("https://whispering-fortress-7282.herokuapp.com/") .build() .create(HackerNewsService.class); } @Provides @Singleton LoginService providesLoginService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setClient(okClient) .setLogLevel(logLevel) .setConverter(loganSquareConvertor) .setEndpoint("https://news.ycombinator.com") .build() .create(LoginService.class); } @Provides @Singleton
// Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java // public interface HackerNewsService { // @GET("/news") // void getTopStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news") // Observable<List<NodeHNAPIStory>> getTopStories(); // // @GET("/news2") // void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); // // @GET("/news2") // Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); // // @GET("/newest") // void getNewestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/newest") // Observable<List<NodeHNAPIStory>> getNewestStories(); // // @GET("/best") // void getBestStories(Callback<List<NodeHNAPIStory>> callback); // // @GET("/best") // Observable<List<NodeHNAPIStory>> getBestStories(); // // @GET("/show") // Observable<List<NodeHNAPIStory>> getShowStories(); // // @GET("/shownew") // Observable<List<NodeHNAPIStory>> getShowNewStories(); // // @GET("/ask") // Observable<List<NodeHNAPIStory>> getAskStories(); // // @GET("/item/{itemId}") // void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback); // // @GET("/item/{itemId}") // Observable<NodeHNAPIStoryDetail> getItemDetails(@Path("itemId") long itemId); // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoganSquareConvertor.java // public final class LoganSquareConvertor implements Converter { // // @Override // public Object fromBody(TypedInput body, Type type) throws ConversionException { // try { // // Check if the type contains a parametrized list // if (ParameterizedType.class.isAssignableFrom(type.getClass())) { // // Grab the actual type parameter from the parametrized list and delegate to LoganSquare // ParameterizedType parameterized = (ParameterizedType) type; // return LoganSquare.parseList(body.in(), (Class) parameterized.getActualTypeArguments()[0]); // // } else { // // Single elements get parsed immediately // return LoganSquare.parse(body.in(), (Class) type); // } // } catch (Exception e) { // throw new ConversionException(e); // } // } // // @Override // public TypedOutput toBody(Object object) { // try { // // Check if the type contains a parametrized list // if (List.class.isAssignableFrom(object.getClass())) { // // Convert the input to a list first, access the first element and serialize the list // List<Object> list = (List<Object>) object; // if (list.isEmpty()) { // return new TypedString("[]"); // } // else { // Object firstElement = list.get(0); // return new TypedString(LoganSquare.serialize(list, (Class<Object>) firstElement.getClass())); // } // } // else { // // Serialize single elements immediately // return new TypedString(LoganSquare.serialize(object)); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/UserService.java // public interface UserService { // @FormUrlEncoded // @POST("/comment") // Observable<Object> postComment(@Header("Cookie") String cookie, // @Field("goto") String gotoParam, // @Field("hmac") String hmac, // @Field("parent") Long parentId, // @Field("text") String text); // // @GET("/vote") // Observable<Object> vote(@Header("Cookie") String cookie, // @Query("for") Long parentId, // @Query("dir") String direction, // @Query("auth") String auth, // @Query("goto") String gotoParam); // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/NetworkServiceModule.java import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.dwak.holohackernews.app.network.HackerNewsService; import io.dwak.holohackernews.app.network.LoganSquareConvertor; import io.dwak.holohackernews.app.network.LoginService; import io.dwak.holohackernews.app.network.UserService; import retrofit.RestAdapter; import retrofit.client.OkClient; @Provides @Singleton HackerNewsService provideService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setConverter(loganSquareConvertor) .setLogLevel(logLevel) .setClient(okClient) .setEndpoint("https://whispering-fortress-7282.herokuapp.com/") .build() .create(HackerNewsService.class); } @Provides @Singleton LoginService providesLoginService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel, @Named("loganSquare") LoganSquareConvertor loganSquareConvertor, @Named("okclient") OkClient okClient) { return new RestAdapter.Builder() .setClient(okClient) .setLogLevel(logLevel) .setConverter(loganSquareConvertor) .setEndpoint("https://news.ycombinator.com") .build() .create(LoginService.class); } @Provides @Singleton
UserService providesUserService(@Named("retrofit-loglevel") RestAdapter.LogLevel logLevel,
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginActivity.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelActivity.java // public abstract class BaseViewModelActivity<T extends BaseViewModel> extends BaseActivity{ // protected abstract T getViewModel(); // // @Override // protected void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // @Override // protected void onPause() { // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/util/UIUtils.java // public class UIUtils { // public static int dpAsPixels(Context context, int densityPixels){ // float scale = context.getResources().getDisplayMetrics().density; // return (int) (densityPixels * scale + 0.5f); // } // // public static void showToast(Context context, String message){ // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.widget.EditText; import com.dd.CircularProgressButton; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxTextView; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.BuildConfig; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseViewModelActivity; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.util.UIUtils; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package io.dwak.holohackernews.app.ui.login; public class LoginActivity extends BaseViewModelActivity<LoginViewModel> { public static final String LOGIN_SUCCESS = "login-success"; public static final String LOGOUT = "logout"; private static final String TAG = LoginActivity.class.getSimpleName(); @InjectView(R.id.username) EditText mUsername; @InjectView(R.id.password) EditText mPassword; @InjectView(R.id.login_button_with_progress) CircularProgressButton mLoginButton; @Inject LoginViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); DaggerViewModelComponent.builder()
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelActivity.java // public abstract class BaseViewModelActivity<T extends BaseViewModel> extends BaseActivity{ // protected abstract T getViewModel(); // // @Override // protected void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // @Override // protected void onPause() { // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/util/UIUtils.java // public class UIUtils { // public static int dpAsPixels(Context context, int densityPixels){ // float scale = context.getResources().getDisplayMetrics().density; // return (int) (densityPixels * scale + 0.5f); // } // // public static void showToast(Context context, String message){ // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); // } // // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.widget.EditText; import com.dd.CircularProgressButton; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxTextView; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.BuildConfig; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseViewModelActivity; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.util.UIUtils; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package io.dwak.holohackernews.app.ui.login; public class LoginActivity extends BaseViewModelActivity<LoginViewModel> { public static final String LOGIN_SUCCESS = "login-success"; public static final String LOGOUT = "logout"; private static final String TAG = LoginActivity.class.getSimpleName(); @InjectView(R.id.username) EditText mUsername; @InjectView(R.id.password) EditText mPassword; @InjectView(R.id.login_button_with_progress) CircularProgressButton mLoginButton; @Inject LoginViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); DaggerViewModelComponent.builder()
.appComponent(HackerNewsApplication.getAppComponent())
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // }
import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable;
package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid;
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable; package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid;
@Inject LoginService mLoginService;
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // }
import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable;
package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder()
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable; package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder()
.okClientModule(new OkClientModule(interceptors))
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // }
import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable;
package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder() .okClientModule(new OkClientModule(interceptors))
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable; package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder() .okClientModule(new OkClientModule(interceptors))
.appModule(HackerNewsApplication.getAppModule())
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // }
import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable;
package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder() .okClientModule(new OkClientModule(interceptors)) .appModule(HackerNewsApplication.getAppModule()) .appComponent(HackerNewsApplication.getAppComponent()) .build() .inject(this); }
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModel.java // public class BaseViewModel { // public void onAttachToView() { // } // // public void onDetachFromView() { // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/OkClientModule.java // @Module // public class OkClientModule { // List<Interceptor> mInterceptorList; // // public OkClientModule() { // } // // public OkClientModule(List<Interceptor> interceptorList) { // mInterceptorList = interceptorList; // } // // @Provides // @Named("okclient") // OkClient providesOkClient(){ // OkHttpClient okHttpClient = new OkHttpClient(); // okHttpClient.setFollowRedirects(true); // okHttpClient.setFollowSslRedirects(true); // // if(mInterceptorList != null){ // okHttpClient.networkInterceptors().addAll(mInterceptorList); // } // // okHttpClient.networkInterceptors().add(new StethoInterceptor()); // // return new OkClient(okHttpClient); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/User.java // public class User extends SugarRecord<User>{ // private String userName; // private String userCookie; // private boolean isCurrentUser; // // public User() { // } // // public User(String userName, String userCookie, boolean isCurrentUser) { // this.userName = userName; // this.userCookie = userCookie; // this.isCurrentUser = isCurrentUser; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserCookie() { // return userCookie; // } // // public void setUserCookie(String userCookie) { // this.userCookie = userCookie; // } // // public boolean isCurrentUser() { // return isCurrentUser; // } // // public void setIsCurrentUser(boolean isCurrentUser) { // this.isCurrentUser = isCurrentUser; // } // // public static boolean isLoggedIn() { // return count(User.class, null, null) > 0; // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/LoginService.java // public interface LoginService { // @FormUrlEncoded // @POST("/login") // Observable<Response> login(@Field("go_to") String goTo, @Field("acct") String username, @Field("pw") String password); // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/login/LoginViewModel.java import android.text.TextUtils; import com.facebook.stetho.okhttp.StethoInterceptor; import com.orm.SugarRecord; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Response; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.base.BaseViewModel; import io.dwak.holohackernews.app.dagger.component.DaggerNetworkServiceComponent; import io.dwak.holohackernews.app.dagger.module.OkClientModule; import io.dwak.holohackernews.app.models.User; import io.dwak.holohackernews.app.network.LoginService; import rx.Observable; package io.dwak.holohackernews.app.ui.login; public class LoginViewModel extends BaseViewModel { String mCfduid; @Inject LoginService mLoginService; String mUserCookie; public LoginViewModel() { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(new StethoInterceptor()); interceptors.add(chain -> { Response response = chain.proceed(chain.request()); List<String> cookieHeaders = response.headers("set-cookie"); for (String header : cookieHeaders) { if (header.contains("user")) { mUserCookie = header.split(";")[0]; } else if(header.contains("__cfduid")){ mCfduid = header.split(";")[0]; } } return response; }); DaggerNetworkServiceComponent.builder() .okClientModule(new OkClientModule(interceptors)) .appModule(HackerNewsApplication.getAppModule()) .appComponent(HackerNewsApplication.getAppComponent()) .build() .inject(this); }
public Observable<User> login(String username, String password) {
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // }
import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.preferences.UserPreferenceManager;
package io.dwak.holohackernews.app.base; public class BaseActivity extends RxAppCompatActivity{ Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.preferences.UserPreferenceManager; package io.dwak.holohackernews.app.base; public class BaseActivity extends RxAppCompatActivity{ Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled()
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/component/SharedPreferencesComponent.java
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/SharedPreferencesModule.java // @Module(includes = AppModule.class) // public class SharedPreferencesModule { // @Provides // @Singleton // SharedPreferences providesSharedPreferences(@Named("context") Context context){ // return PreferenceManager.getDefaultSharedPreferences(context); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // }
import javax.inject.Singleton; import dagger.Component; import io.dwak.holohackernews.app.dagger.module.SharedPreferencesModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; import io.dwak.holohackernews.app.preferences.UserPreferenceManager;
package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = SharedPreferencesModule.class) @Singleton public interface SharedPreferencesComponent {
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/SharedPreferencesModule.java // @Module(includes = AppModule.class) // public class SharedPreferencesModule { // @Provides // @Singleton // SharedPreferences providesSharedPreferences(@Named("context") Context context){ // return PreferenceManager.getDefaultSharedPreferences(context); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/SharedPreferencesComponent.java import javax.inject.Singleton; import dagger.Component; import io.dwak.holohackernews.app.dagger.module.SharedPreferencesModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; import io.dwak.holohackernews.app.preferences.UserPreferenceManager; package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = SharedPreferencesModule.class) @Singleton public interface SharedPreferencesComponent {
void inject(UserPreferenceManager userPreferenceManager);
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/component/SharedPreferencesComponent.java
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/SharedPreferencesModule.java // @Module(includes = AppModule.class) // public class SharedPreferencesModule { // @Provides // @Singleton // SharedPreferences providesSharedPreferences(@Named("context") Context context){ // return PreferenceManager.getDefaultSharedPreferences(context); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // }
import javax.inject.Singleton; import dagger.Component; import io.dwak.holohackernews.app.dagger.module.SharedPreferencesModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; import io.dwak.holohackernews.app.preferences.UserPreferenceManager;
package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = SharedPreferencesModule.class) @Singleton public interface SharedPreferencesComponent { void inject(UserPreferenceManager userPreferenceManager);
// Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/SharedPreferencesModule.java // @Module(includes = AppModule.class) // public class SharedPreferencesModule { // @Provides // @Singleton // SharedPreferences providesSharedPreferences(@Named("context") Context context){ // return PreferenceManager.getDefaultSharedPreferences(context); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java // public class LocalDataManager { // public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; // public static final String OPEN_COUNT = "OPEN_COUNT"; // private static LocalDataManager sInstance; // @Inject SharedPreferences mPreferences; // // private LocalDataManager(@NonNull Context context) { // DaggerSharedPreferencesComponent.builder() // .appComponent(HackerNewsApplication.getAppComponent()) // .appModule(HackerNewsApplication.getAppModule()) // .build() // .inject(this); // mPreferences.edit().commit(); // } // // public static void initialize(@NonNull Context context) { // if (sInstance == null) { // sInstance = new LocalDataManager(context); // } // else { // throw new RuntimeException(LocalDataManager.class.getSimpleName() + " has already been initialized!"); // } // } // // public static LocalDataManager getInstance() { // return sInstance; // } // // public boolean isReturningUser() { // return getBoolean(PREF_RETURNING_USER); // } // // public void setReturningUser(boolean isFirstRun) { // set(PREF_RETURNING_USER, isFirstRun); // } // // public int getOpenCount(){ // return getInt(OPEN_COUNT); // } // // public void addOpenCount(){ // int openCount = getOpenCount(); // set(OPEN_COUNT, ++openCount); // } // // private void set(String key, int i) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putInt(key, i); // editor.apply(); // } // // private int getInt(String key){ // return mPreferences.getInt(key, 0); // } // private boolean getBoolean(String key) { // return mPreferences.getBoolean(key, false); // } // // @Nullable // private String getString(String key) { // return mPreferences.getString(key, null); // } // // private void set(@NonNull String key, boolean value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // private void set(@NonNull String key, String value) { // SharedPreferences.Editor editor = mPreferences.edit(); // editor.putString(key, value); // editor.apply(); // } // // private void remove(@NonNull String key) { // mPreferences.edit().remove(key).apply(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/SharedPreferencesComponent.java import javax.inject.Singleton; import dagger.Component; import io.dwak.holohackernews.app.dagger.module.SharedPreferencesModule; import io.dwak.holohackernews.app.preferences.LocalDataManager; import io.dwak.holohackernews.app.preferences.UserPreferenceManager; package io.dwak.holohackernews.app.dagger.component; @Component(dependencies = AppComponent.class, modules = SharedPreferencesModule.class) @Singleton public interface SharedPreferencesComponent { void inject(UserPreferenceManager userPreferenceManager);
void inject(LocalDataManager localDataManager);
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java
// Path: app/src/main/java/io/dwak/holohackernews/app/cache/CacheManager.java // public class CacheManager { // private static final int DEFAULT_CACHE_SIZE = 1024 * 1024 * 10; // private static final int DEFAULT_MEM_CACHE_SIZE = 20; // private static final int VALUE_COUNT = 1; // private static final String HASH_ALGORITHM = "MD5"; // private static final String STRING_ENCODING = "UTF-8"; // private DiskLruCache mDiskLruCache; // private final LruCache mMemCache; // private final File mDirectory; // private Gson mGson; // private static CacheManager sCacheManager; // // public static CacheManager getInstance(Context context, Gson gson){ // if(sCacheManager == null){ // sCacheManager = new CacheManager(context, gson); // } // // return sCacheManager; // } // public CacheManager() { // mDiskLruCache = null; // mMemCache = null; // mDirectory = null; // mGson = null; // } // // public CacheManager(Context context, Gson gson){ // mDirectory= new File(context.getCacheDir() + "/cache"); // if (!mDirectory.exists()) { // mDirectory.mkdirs(); // } // mMemCache = new LruCache(DEFAULT_MEM_CACHE_SIZE); // mGson = gson; // open(); // } // // private void open() { // try { // mDiskLruCache = DiskLruCache.open(mDirectory, BuildConfig.VERSION_CODE, VALUE_COUNT, DEFAULT_CACHE_SIZE); // } catch (IOException e) { // Thread.dumpStack(); // } // } // // // public void clear() throws IOException { // mDiskLruCache.delete(); // mMemCache.evictAll(); // open(); // } // // public boolean delete(String key) throws IOException { // mMemCache.remove(key); // return mDiskLruCache.remove(getHashOf(key)); // } // // public <T> T get(String key, Type type) throws IOException { // T ob = (T) mMemCache.get(key); // if (ob != null) { // return ob; // } // DiskLruCache.Snapshot snapshot = mDiskLruCache.get(getHashOf(key)); // if (snapshot != null) { // String value = snapshot.getString(0); // ob = mGson.fromJson(value, type); // } // return ob; // } // // public void put(String key, Object object) throws IOException { // mMemCache.put(key, object); // DiskLruCache.Editor editor = null; // try { // editor = mDiskLruCache.edit(getHashOf(key)); // if (editor == null) { // return; // } // if (writeValueToCache(mGson.toJson(object), editor)) { // mDiskLruCache.flush(); // editor.commit(); // } // else { // editor.abort(); // } // } catch (IOException e) { // if (editor != null) { // editor.abort(); // } // // throw e; // } // // } // // protected boolean writeValueToCache(String value, DiskLruCache.Editor editor) throws IOException { // OutputStream outputStream = null; // try { // outputStream = new BufferedOutputStream(editor.newOutputStream(0)); // outputStream.write(value.getBytes(STRING_ENCODING)); // } finally { // if (outputStream != null) { // outputStream.close(); // } // } // // return true; // } // // // protected String getHashOf(String string) throws UnsupportedEncodingException { // try { // MessageDigest messageDigest = null; // messageDigest = MessageDigest.getInstance(HASH_ALGORITHM); // messageDigest.update(string.getBytes(STRING_ENCODING)); // byte[] digest = messageDigest.digest(); // BigInteger bigInt = new BigInteger(1, digest); // // return bigInt.toString(16); // } catch (NoSuchAlgorithmException e) { // // return string; // } // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // }
import android.app.Application; import android.content.res.Resources; import javax.inject.Named; import dagger.Component; import io.dwak.holohackernews.app.cache.CacheManager; import io.dwak.holohackernews.app.dagger.module.AppModule;
package io.dwak.holohackernews.app.dagger.component; @Component(modules = {AppModule.class}) public interface AppComponent { void inject(Application application); @Named(AppModule.CACHE_MANAGER)
// Path: app/src/main/java/io/dwak/holohackernews/app/cache/CacheManager.java // public class CacheManager { // private static final int DEFAULT_CACHE_SIZE = 1024 * 1024 * 10; // private static final int DEFAULT_MEM_CACHE_SIZE = 20; // private static final int VALUE_COUNT = 1; // private static final String HASH_ALGORITHM = "MD5"; // private static final String STRING_ENCODING = "UTF-8"; // private DiskLruCache mDiskLruCache; // private final LruCache mMemCache; // private final File mDirectory; // private Gson mGson; // private static CacheManager sCacheManager; // // public static CacheManager getInstance(Context context, Gson gson){ // if(sCacheManager == null){ // sCacheManager = new CacheManager(context, gson); // } // // return sCacheManager; // } // public CacheManager() { // mDiskLruCache = null; // mMemCache = null; // mDirectory = null; // mGson = null; // } // // public CacheManager(Context context, Gson gson){ // mDirectory= new File(context.getCacheDir() + "/cache"); // if (!mDirectory.exists()) { // mDirectory.mkdirs(); // } // mMemCache = new LruCache(DEFAULT_MEM_CACHE_SIZE); // mGson = gson; // open(); // } // // private void open() { // try { // mDiskLruCache = DiskLruCache.open(mDirectory, BuildConfig.VERSION_CODE, VALUE_COUNT, DEFAULT_CACHE_SIZE); // } catch (IOException e) { // Thread.dumpStack(); // } // } // // // public void clear() throws IOException { // mDiskLruCache.delete(); // mMemCache.evictAll(); // open(); // } // // public boolean delete(String key) throws IOException { // mMemCache.remove(key); // return mDiskLruCache.remove(getHashOf(key)); // } // // public <T> T get(String key, Type type) throws IOException { // T ob = (T) mMemCache.get(key); // if (ob != null) { // return ob; // } // DiskLruCache.Snapshot snapshot = mDiskLruCache.get(getHashOf(key)); // if (snapshot != null) { // String value = snapshot.getString(0); // ob = mGson.fromJson(value, type); // } // return ob; // } // // public void put(String key, Object object) throws IOException { // mMemCache.put(key, object); // DiskLruCache.Editor editor = null; // try { // editor = mDiskLruCache.edit(getHashOf(key)); // if (editor == null) { // return; // } // if (writeValueToCache(mGson.toJson(object), editor)) { // mDiskLruCache.flush(); // editor.commit(); // } // else { // editor.abort(); // } // } catch (IOException e) { // if (editor != null) { // editor.abort(); // } // // throw e; // } // // } // // protected boolean writeValueToCache(String value, DiskLruCache.Editor editor) throws IOException { // OutputStream outputStream = null; // try { // outputStream = new BufferedOutputStream(editor.newOutputStream(0)); // outputStream.write(value.getBytes(STRING_ENCODING)); // } finally { // if (outputStream != null) { // outputStream.close(); // } // } // // return true; // } // // // protected String getHashOf(String string) throws UnsupportedEncodingException { // try { // MessageDigest messageDigest = null; // messageDigest = MessageDigest.getInstance(HASH_ALGORITHM); // messageDigest.update(string.getBytes(STRING_ENCODING)); // byte[] digest = messageDigest.digest(); // BigInteger bigInt = new BigInteger(1, digest); // // return bigInt.toString(16); // } catch (NoSuchAlgorithmException e) { // // return string; // } // } // // } // // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/module/AppModule.java // @Module // public class AppModule { // public static final String CACHE_MANAGER = "cacheManager"; // public static final String RESOURCES = "resources"; // Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Provides // @Named("context") // Context providesApplication() { // return mApplication; // } // // // @Provides // @Named(RESOURCES) // Resources providesResources() { // return mApplication.getResources(); // } // // @Provides // @Named("gson") // Gson providesGson() { // return new GsonBuilder().registerTypeAdapter(Long.class, new LongTypeAdapter()) // .create(); // } // // @Provides // @Singleton // @Named("loganSquare") // LoganSquareConvertor providesLoganSquare(){ // return new LoganSquareConvertor(); // } // // @Provides // @Named("retrofit-loglevel") // RestAdapter.LogLevel providesLogLevel(){ // if(BuildConfig.DEBUG) { // return RestAdapter.LogLevel.FULL; // } // else { // return RestAdapter.LogLevel.NONE; // } // } // // @Provides // @Named(CACHE_MANAGER) // CacheManager providesCacheManager(@Named("context")Context context, // @Named("gson") Gson gson){ // return CacheManager.getInstance(context, gson); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/dagger/component/AppComponent.java import android.app.Application; import android.content.res.Resources; import javax.inject.Named; import dagger.Component; import io.dwak.holohackernews.app.cache.CacheManager; import io.dwak.holohackernews.app.dagger.module.AppModule; package io.dwak.holohackernews.app.dagger.component; @Component(modules = {AppModule.class}) public interface AppComponent { void inject(Application application); @Named(AppModule.CACHE_MANAGER)
CacheManager getCacheManager();
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // }
import android.content.SharedPreferences; import android.support.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.dagger.component.DaggerSharedPreferencesComponent;
package io.dwak.holohackernews.app.preferences; public class UserPreferenceManager { public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; public static final String PREF_LINK_FIRST = "pref_link_first"; public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; public static final String PREF_NIGHT_MODE = "pref_night_mode"; public static final String PREF_TEXT_SIZE = "pref_text_size"; public static final String PREF_SWIPE_BACK = "pref_swipe_back"; @Retention(RetentionPolicy.SOURCE) @StringDef({SMALL, MEDIUM, LARGE}) public @interface TextSize{} public static final String SMALL = "small"; public static final String MEDIUM = "medium"; public static final String LARGE = "large"; public static UserPreferenceManager sInstance; @Inject SharedPreferences mSharedPreferences; public static UserPreferenceManager getInstance(){ if(sInstance == null){ sInstance = new UserPreferenceManager(); } return sInstance; } public UserPreferenceManager() { DaggerSharedPreferencesComponent.builder()
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java import android.content.SharedPreferences; import android.support.annotation.StringDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.dagger.component.DaggerSharedPreferencesComponent; package io.dwak.holohackernews.app.preferences; public class UserPreferenceManager { public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; public static final String PREF_LINK_FIRST = "pref_link_first"; public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; public static final String PREF_NIGHT_MODE = "pref_night_mode"; public static final String PREF_TEXT_SIZE = "pref_text_size"; public static final String PREF_SWIPE_BACK = "pref_swipe_back"; @Retention(RetentionPolicy.SOURCE) @StringDef({SMALL, MEDIUM, LARGE}) public @interface TextSize{} public static final String SMALL = "small"; public static final String MEDIUM = "medium"; public static final String LARGE = "large"; public static UserPreferenceManager sInstance; @Inject SharedPreferences mSharedPreferences; public static UserPreferenceManager getInstance(){ if(sInstance == null){ sInstance = new UserPreferenceManager(); } return sInstance; } public UserPreferenceManager() { DaggerSharedPreferencesComponent.builder()
.appModule(HackerNewsApplication.getAppModule())
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense;
package io.dwak.holohackernews.app.ui.about; public class AboutActivity extends BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if(toolbar !=null){ toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(v -> finish()); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } }
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense; package io.dwak.holohackernews.app.ui.about; public class AboutActivity extends BaseActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if(toolbar !=null){ toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(v -> finish()); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } }
public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> {
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense;
super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if(toolbar !=null){ toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(v -> finish()); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } } public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> { @Inject AboutViewModel mViewModel; @InjectView(R.id.recycler_view) RecyclerView mRecyclerView; public static Fragment newInstance() { return new AboutFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); ButterKnife.inject(this, view); DaggerViewModelComponent.builder()
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense; super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if(toolbar !=null){ toolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); toolbar.setNavigationOnClickListener(v -> finish()); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } } public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> { @Inject AboutViewModel mViewModel; @InjectView(R.id.recycler_view) RecyclerView mRecyclerView; public static Fragment newInstance() { return new AboutFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); ButterKnife.inject(this, view); DaggerViewModelComponent.builder()
.appComponent(HackerNewsApplication.getAppComponent())
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense;
} if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } } public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> { @Inject AboutViewModel mViewModel; @InjectView(R.id.recycler_view) RecyclerView mRecyclerView; public static Fragment newInstance() { return new AboutFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); ButterKnife.inject(this, view); DaggerViewModelComponent.builder() .appComponent(HackerNewsApplication.getAppComponent()) .build() .inject(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); AboutAdapter aboutAdapter = new AboutAdapter(); mRecyclerView.setAdapter(aboutAdapter); aboutAdapter.addHeader();
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseActivity.java // public class BaseActivity extends RxAppCompatActivity{ // Toolbar mToolbar; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ // getWindow().setStatusBarColor(getResources().getColor(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.color.colorPrimaryDarkNight // : R.color.colorPrimaryDark)); // } // // setTheme(UserPreferenceManager.getInstance().isNightModeEnabled() // ? R.style.AppThemeNight // : R.style.AppTheme); // } // // public Toolbar getToolbar(){ // if (mToolbar == null) { // mToolbar = (Toolbar) findViewById(R.id.toolbar); // if (mToolbar != null) { // setSupportActionBar(mToolbar); // } // } // return mToolbar; // } // // @Override // protected void onResume() { // super.onResume(); // if (getToolbar() != null) { // if (UserPreferenceManager.getInstance().isNightModeEnabled()) { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimaryDarkNight)); // } // else { // getToolbar().setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // } // } // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/base/BaseViewModelFragment.java // public abstract class BaseViewModelFragment<T extends BaseViewModel> extends BaseFragment { // protected abstract T getViewModel(); // // @Override // public void onResume() { // super.onResume(); // getViewModel().onAttachToView(); // } // // public void onPause(){ // super.onPause(); // getViewModel().onDetachFromView(); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutActivity.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.base.BaseActivity; import io.dwak.holohackernews.app.base.BaseViewModelFragment; import io.dwak.holohackernews.app.dagger.component.DaggerViewModelComponent; import io.dwak.holohackernews.app.models.AboutLicense; } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, AboutFragment.newInstance()) .commit(); } } public static class AboutFragment extends BaseViewModelFragment<AboutViewModel> { @Inject AboutViewModel mViewModel; @InjectView(R.id.recycler_view) RecyclerView mRecyclerView; public static Fragment newInstance() { return new AboutFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); ButterKnife.inject(this, view); DaggerViewModelComponent.builder() .appComponent(HackerNewsApplication.getAppComponent()) .build() .inject(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); AboutAdapter aboutAdapter = new AboutAdapter(); mRecyclerView.setAdapter(aboutAdapter); aboutAdapter.addHeader();
for (AboutLicense license : getViewModel().getLicenses()) {
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutAdapter.java
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // }
import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.dwak.holohackernews.app.models.AboutLicense;
package io.dwak.holohackernews.app.ui.about; public class AboutAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { List<AboutItem> mList; public AboutAdapter() { mList = new ArrayList<>(); } public void addHeader() { mList.add(0, new AboutItem<>(null, AboutItem.HEADER)); notifyItemInserted(0); }
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutAdapter.java import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.dwak.holohackernews.app.models.AboutLicense; package io.dwak.holohackernews.app.ui.about; public class AboutAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { List<AboutItem> mList; public AboutAdapter() { mList = new ArrayList<>(); } public void addHeader() { mList.add(0, new AboutItem<>(null, AboutItem.HEADER)); notifyItemInserted(0); }
public void addLicense(AboutLicense aboutLicense) {
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/models/Story.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // }
import android.os.Parcel; import android.os.Parcelable; import com.orm.SugarRecord; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory;
package io.dwak.holohackernews.app.models; public class Story extends SugarRecord<Story> implements Parcelable { private Long mStoryId; private String mTitle; private String mUrl; private String mDomain; private int mPoints; private String mSubmitter; private String mPublishedTime; private int mNumComments; private String mType; private boolean isSaved; private boolean mIsRead; public Story() { } private Story(Long storyId, String title, String url, String domain, int points, String submitter, String publishedTime, int numComments, String type) { mStoryId = storyId; mTitle = title; mUrl = url; mDomain = domain; mPoints = points; mSubmitter = submitter; mPublishedTime = publishedTime; mNumComments = numComments; mType = type; }
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/models/Story.java import android.os.Parcel; import android.os.Parcelable; import com.orm.SugarRecord; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory; package io.dwak.holohackernews.app.models; public class Story extends SugarRecord<Story> implements Parcelable { private Long mStoryId; private String mTitle; private String mUrl; private String mDomain; private int mPoints; private String mSubmitter; private String mPublishedTime; private int mNumComments; private String mType; private boolean isSaved; private boolean mIsRead; public Story() { } private Story(Long storyId, String title, String url, String domain, int points, String submitter, String publishedTime, int numComments, String type) { mStoryId = storyId; mTitle = title; mUrl = url; mDomain = domain; mPoints = points; mSubmitter = submitter; mPublishedTime = publishedTime; mNumComments = numComments; mType = type; }
public static Story fromNodeHNAPIStory(NodeHNAPIStory nodeHNAPIStory) {
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutLicenseItemViewHolder.java
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // }
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 butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.models.AboutLicense;
package io.dwak.holohackernews.app.ui.about; public class AboutLicenseItemViewHolder extends RecyclerView.ViewHolder{ @InjectView(R.id.name) public TextView name; @InjectView(R.id.license) public TextView license; public AboutLicenseItemViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); } public static AboutLicenseItemViewHolder create(Context context, ViewGroup parent){ return new AboutLicenseItemViewHolder(LayoutInflater.from(context).inflate(R.layout.item_about_license, parent, false)); }
// Path: app/src/main/java/io/dwak/holohackernews/app/models/AboutLicense.java // public class AboutLicense { // public final int nameResId; // public final int licenseResId; // // public AboutLicense(int nameResId, int license) { // this.nameResId = nameResId; // this.licenseResId = license; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/about/AboutLicenseItemViewHolder.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 butterknife.ButterKnife; import butterknife.InjectView; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.models.AboutLicense; package io.dwak.holohackernews.app.ui.about; public class AboutLicenseItemViewHolder extends RecyclerView.ViewHolder{ @InjectView(R.id.name) public TextView name; @InjectView(R.id.license) public TextView license; public AboutLicenseItemViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); } public static AboutLicenseItemViewHolder create(Context context, ViewGroup parent){ return new AboutLicenseItemViewHolder(LayoutInflater.from(context).inflate(R.layout.item_about_license, parent, false)); }
public static void bind(AboutLicenseItemViewHolder holder, AboutLicense license){
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStoryDetail.java // @JsonObject // public class NodeHNAPIStoryDetail { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public Integer points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public Integer commentsCount; // @JsonField(name = "content") public String content; // @JsonField(name = "poll") public Object poll; // @JsonField(name = "link") public String link; // @JsonField(name = "comments") public List<NodeHNAPIComment> commentList; // @JsonField(name = "more_comments_id") public Long moreCommentsId; // @JsonField(name = "type") public String type; // // }
import java.util.List; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory; import io.dwak.holohackernews.app.network.models.NodeHNAPIStoryDetail; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import rx.Observable;
package io.dwak.holohackernews.app.network; /** * Retrofit service to interface with hacker news api * Created by vishnu on 4/21/14. */ public interface HackerNewsService { @GET("/news")
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStoryDetail.java // @JsonObject // public class NodeHNAPIStoryDetail { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public Integer points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public Integer commentsCount; // @JsonField(name = "content") public String content; // @JsonField(name = "poll") public Object poll; // @JsonField(name = "link") public String link; // @JsonField(name = "comments") public List<NodeHNAPIComment> commentList; // @JsonField(name = "more_comments_id") public Long moreCommentsId; // @JsonField(name = "type") public String type; // // } // Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java import java.util.List; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory; import io.dwak.holohackernews.app.network.models.NodeHNAPIStoryDetail; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import rx.Observable; package io.dwak.holohackernews.app.network; /** * Retrofit service to interface with hacker news api * Created by vishnu on 4/21/14. */ public interface HackerNewsService { @GET("/news")
void getTopStories(Callback<List<NodeHNAPIStory>> callback);
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStoryDetail.java // @JsonObject // public class NodeHNAPIStoryDetail { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public Integer points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public Integer commentsCount; // @JsonField(name = "content") public String content; // @JsonField(name = "poll") public Object poll; // @JsonField(name = "link") public String link; // @JsonField(name = "comments") public List<NodeHNAPIComment> commentList; // @JsonField(name = "more_comments_id") public Long moreCommentsId; // @JsonField(name = "type") public String type; // // }
import java.util.List; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory; import io.dwak.holohackernews.app.network.models.NodeHNAPIStoryDetail; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import rx.Observable;
package io.dwak.holohackernews.app.network; /** * Retrofit service to interface with hacker news api * Created by vishnu on 4/21/14. */ public interface HackerNewsService { @GET("/news") void getTopStories(Callback<List<NodeHNAPIStory>> callback); @GET("/news") Observable<List<NodeHNAPIStory>> getTopStories(); @GET("/news2") void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); @GET("/news2") Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); @GET("/newest") void getNewestStories(Callback<List<NodeHNAPIStory>> callback); @GET("/newest") Observable<List<NodeHNAPIStory>> getNewestStories(); @GET("/best") void getBestStories(Callback<List<NodeHNAPIStory>> callback); @GET("/best") Observable<List<NodeHNAPIStory>> getBestStories(); @GET("/show") Observable<List<NodeHNAPIStory>> getShowStories(); @GET("/shownew") Observable<List<NodeHNAPIStory>> getShowNewStories(); @GET("/ask") Observable<List<NodeHNAPIStory>> getAskStories(); @GET("/item/{itemId}")
// Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStory.java // @JsonObject // public class NodeHNAPIStory { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public int points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public int commentsCount; // @JsonField(name = "type") public String type; // // public NodeHNAPIStory() { // } // // private NodeHNAPIStory(Long id, String title, String url, String domain, int points, String user, String timeAgo, int commentsCount, String type) { // this.id = id; // this.title = title; // this.url = url; // this.domain = domain; // this.points = points; // this.user = user; // this.timeAgo = timeAgo; // this.commentsCount = commentsCount; // this.type = type; // } // // // public static NodeHNAPIStory fromStory(Story story) { // return new NodeHNAPIStory(story.getStoryId(), // story.getTitle(), // story.getUrl(), // story.getDomain(), // story.getPoints(), // story.getSubmitter(), // story.getPublishedTime(), // story.getNumComments(), // story.getType()); // } // } // // Path: app/src/main/java/io/dwak/holohackernews/app/network/models/NodeHNAPIStoryDetail.java // @JsonObject // public class NodeHNAPIStoryDetail { // @JsonField(name = "id") public Long id; // @JsonField(name = "title") public String title; // @JsonField(name = "url") public String url; // @JsonField(name = "domain") public String domain; // @JsonField(name = "points") public Integer points; // @JsonField(name = "user") public String user; // @JsonField(name = "time_ago") public String timeAgo; // @JsonField(name = "comments_count") public Integer commentsCount; // @JsonField(name = "content") public String content; // @JsonField(name = "poll") public Object poll; // @JsonField(name = "link") public String link; // @JsonField(name = "comments") public List<NodeHNAPIComment> commentList; // @JsonField(name = "more_comments_id") public Long moreCommentsId; // @JsonField(name = "type") public String type; // // } // Path: app/src/main/java/io/dwak/holohackernews/app/network/HackerNewsService.java import java.util.List; import io.dwak.holohackernews.app.network.models.NodeHNAPIStory; import io.dwak.holohackernews.app.network.models.NodeHNAPIStoryDetail; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import rx.Observable; package io.dwak.holohackernews.app.network; /** * Retrofit service to interface with hacker news api * Created by vishnu on 4/21/14. */ public interface HackerNewsService { @GET("/news") void getTopStories(Callback<List<NodeHNAPIStory>> callback); @GET("/news") Observable<List<NodeHNAPIStory>> getTopStories(); @GET("/news2") void getTopStoriesPageTwo(Callback<List<NodeHNAPIStory>> callback); @GET("/news2") Observable<List<NodeHNAPIStory>> getTopStoriesPageTwo(); @GET("/newest") void getNewestStories(Callback<List<NodeHNAPIStory>> callback); @GET("/newest") Observable<List<NodeHNAPIStory>> getNewestStories(); @GET("/best") void getBestStories(Callback<List<NodeHNAPIStory>> callback); @GET("/best") Observable<List<NodeHNAPIStory>> getBestStories(); @GET("/show") Observable<List<NodeHNAPIStory>> getShowStories(); @GET("/shownew") Observable<List<NodeHNAPIStory>> getShowNewStories(); @GET("/ask") Observable<List<NodeHNAPIStory>> getAskStories(); @GET("/item/{itemId}")
void getItemDetails(@Path("itemId") long itemId, Callback<NodeHNAPIStoryDetail> callback);
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/util/HNLog.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // }
import android.support.annotation.NonNull; import android.util.Log; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.dwak.holohackernews.app.HackerNewsApplication;
package io.dwak.holohackernews.app.util; /** * This class contains passthrough methods to {@link Log} that only print if debugging is enabled * on the {@link HackerNewsApplication} class */ public class HNLog { private static final Pattern ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$"); public static void d(@NonNull String message){
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/util/HNLog.java import android.support.annotation.NonNull; import android.util.Log; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.dwak.holohackernews.app.HackerNewsApplication; package io.dwak.holohackernews.app.util; /** * This class contains passthrough methods to {@link Log} that only print if debugging is enabled * on the {@link HackerNewsApplication} class */ public class HNLog { private static final Pattern ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$"); public static void d(@NonNull String message){
if(HackerNewsApplication.isDebug()){
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/storylist/navigation/NavigationDrawerAdapter.java
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // }
import android.app.Activity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.preferences.UserPreferenceManager;
package io.dwak.holohackernews.app.ui.storylist.navigation; @Deprecated public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItem> { private final Context mContext; public NavigationDrawerAdapter(Context context, int resource, List<NavigationDrawerItem> navigationDrawerItems) { super(context, resource, navigationDrawerItems); mContext = context; } @Override public View getView(int position, View view, ViewGroup viewGroup) { if (getItem(position).shouldDisplayIcon()) { view = ((Activity) mContext).getLayoutInflater()
// Path: app/src/main/java/io/dwak/holohackernews/app/preferences/UserPreferenceManager.java // public class UserPreferenceManager { // // public static final String SHOULD_USE_EXTERNAL_BROWSER = "pref_system_browser"; // public static final String PREF_LINK_FIRST = "pref_link_first"; // public static final String PREF_LIST_ANIMATIONS = "pref_list_animations"; // public static final String PREF_NIGHT_MODE = "pref_night_mode"; // public static final String PREF_TEXT_SIZE = "pref_text_size"; // public static final String PREF_SWIPE_BACK = "pref_swipe_back"; // // @Retention(RetentionPolicy.SOURCE) // @StringDef({SMALL, MEDIUM, LARGE}) // public @interface TextSize{} // public static final String SMALL = "small"; // public static final String MEDIUM = "medium"; // public static final String LARGE = "large"; // // public static UserPreferenceManager sInstance; // @Inject SharedPreferences mSharedPreferences; // // public static UserPreferenceManager getInstance(){ // if(sInstance == null){ // sInstance = new UserPreferenceManager(); // } // return sInstance; // } // // public UserPreferenceManager() { // DaggerSharedPreferencesComponent.builder() // .appModule(HackerNewsApplication.getAppModule()) // .appComponent(HackerNewsApplication.getAppComponent()) // .build() // .inject(this); // sInstance = this; // } // // public boolean showLinkFirst(){ // return mSharedPreferences.getBoolean(PREF_LINK_FIRST, false); // } // // public @TextSize String getPreferredTextSize(){ // //noinspection ResourceType // return mSharedPreferences.getString(PREF_TEXT_SIZE, SMALL); // } // // public boolean isExternalBrowserEnabled(){ // return mSharedPreferences.getBoolean(SHOULD_USE_EXTERNAL_BROWSER, false); // } // // public void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.registerOnSharedPreferenceChangeListener(listener); // } // // public void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { // mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); // } // // public boolean isNightModeEnabled(){ // return mSharedPreferences.getBoolean(PREF_NIGHT_MODE, false); // } // // public boolean isSwipeBackEnabled(){ // return mSharedPreferences.getBoolean(PREF_SWIPE_BACK, true); // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/storylist/navigation/NavigationDrawerAdapter.java import android.app.Activity; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import io.dwak.holohackernews.app.R; import io.dwak.holohackernews.app.preferences.UserPreferenceManager; package io.dwak.holohackernews.app.ui.storylist.navigation; @Deprecated public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItem> { private final Context mContext; public NavigationDrawerAdapter(Context context, int resource, List<NavigationDrawerItem> navigationDrawerItems) { super(context, resource, navigationDrawerItems); mContext = context; } @Override public View getView(int position, View view, ViewGroup viewGroup) { if (getItem(position).shouldDisplayIcon()) { view = ((Activity) mContext).getLayoutInflater()
.inflate(UserPreferenceManager.getInstance().isNightModeEnabled()
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.dagger.component.DaggerSharedPreferencesComponent;
package io.dwak.holohackernews.app.preferences; public class LocalDataManager { public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; public static final String OPEN_COUNT = "OPEN_COUNT"; private static LocalDataManager sInstance; @Inject SharedPreferences mPreferences; private LocalDataManager(@NonNull Context context) { DaggerSharedPreferencesComponent.builder()
// Path: app/src/main/java/io/dwak/holohackernews/app/HackerNewsApplication.java // public class HackerNewsApplication extends SugarApp { // private static boolean mDebug = BuildConfig.DEBUG; // private static HackerNewsApplication sInstance; // private Context mContext; // private static AppComponent sAppComponent; // // private static AppModule sAppModule; // // @Override // public void onCreate() { // super.onCreate(); // if (sInstance == null) { // sInstance = this; // } // // if("release".equals(BuildConfig.BUILD_TYPE)){ // Bugsnag.init(this); // } // // mContext = getApplicationContext(); // Stetho.initialize( // Stetho.newInitializerBuilder(this) // .enableDumpapp( // Stetho.defaultDumperPluginsProvider(this)) // .enableWebKitInspector( // Stetho.defaultInspectorModulesProvider(this)) // .build()); // // sAppModule = new AppModule(this); // sAppComponent = DaggerAppComponent.builder() // .appModule(sAppModule) // .build(); // sAppComponent.inject(this); // // LocalDataManager.initialize(mContext); // } // // public static boolean isDebug() { // return mDebug; // } // // public static HackerNewsApplication getInstance() { // return sInstance; // } // // public Context getContext() { // return mContext; // } // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // public static AppModule getAppModule(){ // return sAppModule; // } // } // Path: app/src/main/java/io/dwak/holohackernews/app/preferences/LocalDataManager.java import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import javax.inject.Inject; import io.dwak.holohackernews.app.HackerNewsApplication; import io.dwak.holohackernews.app.dagger.component.DaggerSharedPreferencesComponent; package io.dwak.holohackernews.app.preferences; public class LocalDataManager { public static final String PREF_RETURNING_USER = "PREF_RETURNING_USER"; public static final String OPEN_COUNT = "OPEN_COUNT"; private static LocalDataManager sInstance; @Inject SharedPreferences mPreferences; private LocalDataManager(@NonNull Context context) { DaggerSharedPreferencesComponent.builder()
.appComponent(HackerNewsApplication.getAppComponent())
dinosaurwithakatana/hacker-news-android
app/src/main/java/io/dwak/holohackernews/app/ui/storylist/StoryListAdapter.java
// Path: app/src/main/java/io/dwak/holohackernews/app/models/Story.java // public class Story extends SugarRecord<Story> implements Parcelable { // private Long mStoryId; // private String mTitle; // private String mUrl; // private String mDomain; // private int mPoints; // private String mSubmitter; // private String mPublishedTime; // private int mNumComments; // private String mType; // private boolean isSaved; // private boolean mIsRead; // // public Story() { // } // // private Story(Long storyId, String title, String url, String domain, int points, String submitter, String publishedTime, int numComments, String type) { // mStoryId = storyId; // mTitle = title; // mUrl = url; // mDomain = domain; // mPoints = points; // mSubmitter = submitter; // mPublishedTime = publishedTime; // mNumComments = numComments; // mType = type; // } // // public static Story fromNodeHNAPIStory(NodeHNAPIStory nodeHNAPIStory) { // return new Story(nodeHNAPIStory.id, // nodeHNAPIStory.title, // nodeHNAPIStory.url, // nodeHNAPIStory.domain, // nodeHNAPIStory.points, // nodeHNAPIStory.user, // nodeHNAPIStory.timeAgo, // nodeHNAPIStory.commentsCount, // nodeHNAPIStory.type); // } // // public Long getStoryId() { // return mStoryId; // } // // public String getTitle() { // return mTitle; // } // // public String getUrl() { // return mUrl; // } // // public String getDomain() { // return mDomain; // } // // public int getPoints() { // return mPoints; // } // // public String getSubmitter() { // return mSubmitter; // } // // public String getPublishedTime() { // return mPublishedTime; // } // // public int getNumComments() { // return mNumComments; // } // // public String getType() { // return mType; // } // // public void setStoryId(Long storyId) { // mStoryId = storyId; // } // // public void setTitle(String title) { // mTitle = title; // } // // public void setUrl(String url) { // mUrl = url; // } // // public void setDomain(String domain) { // mDomain = domain; // } // // public void setPoints(int points) { // mPoints = points; // } // // public void setSubmitter(String submitter) { // mSubmitter = submitter; // } // // public void setPublishedTime(String publishedTime) { // mPublishedTime = publishedTime; // } // // public void setNumComments(int numComments) { // mNumComments = numComments; // } // // public void setType(String type) { // mType = type; // } // // public boolean isSaved() { // return isSaved; // } // // public void setIsSaved(boolean isSaved) { // this.isSaved = isSaved; // } // // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Story story = (Story) o; // // if (mStoryId != null ? !mStoryId.equals(story.mStoryId) : story.mStoryId != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return mStoryId != null ? mStoryId.hashCode() : 0; // } // // public boolean isRead() { // return mIsRead; // } // // public void setIsRead(boolean isRead) { // this.mIsRead = isRead; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeValue(this.mStoryId); // dest.writeString(this.mTitle); // dest.writeString(this.mUrl); // dest.writeString(this.mDomain); // dest.writeInt(this.mPoints); // dest.writeString(this.mSubmitter); // dest.writeString(this.mPublishedTime); // dest.writeInt(this.mNumComments); // dest.writeString(this.mType); // dest.writeByte(isSaved ? (byte) 1 : (byte) 0); // dest.writeByte(mIsRead ? (byte) 1 : (byte) 0); // } // // protected Story(Parcel in) { // this.mStoryId = (Long) in.readValue(Long.class.getClassLoader()); // this.mTitle = in.readString(); // this.mUrl = in.readString(); // this.mDomain = in.readString(); // this.mPoints = in.readInt(); // this.mSubmitter = in.readString(); // this.mPublishedTime = in.readString(); // this.mNumComments = in.readInt(); // this.mType = in.readString(); // this.isSaved = in.readByte() != 0; // this.mIsRead = in.readByte() != 0; // } // // public static final Creator<Story> CREATOR = new Creator<Story>() { // public Story createFromParcel(Parcel source) { // return new Story(source); // } // // public Story[] newArray(int size) { // return new Story[size]; // } // }; // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.List; import io.dwak.holohackernews.app.models.Story;
package io.dwak.holohackernews.app.ui.storylist; public class StoryListAdapter extends RecyclerView.Adapter<StoryViewHolder> { @NonNull private final Context mContext;
// Path: app/src/main/java/io/dwak/holohackernews/app/models/Story.java // public class Story extends SugarRecord<Story> implements Parcelable { // private Long mStoryId; // private String mTitle; // private String mUrl; // private String mDomain; // private int mPoints; // private String mSubmitter; // private String mPublishedTime; // private int mNumComments; // private String mType; // private boolean isSaved; // private boolean mIsRead; // // public Story() { // } // // private Story(Long storyId, String title, String url, String domain, int points, String submitter, String publishedTime, int numComments, String type) { // mStoryId = storyId; // mTitle = title; // mUrl = url; // mDomain = domain; // mPoints = points; // mSubmitter = submitter; // mPublishedTime = publishedTime; // mNumComments = numComments; // mType = type; // } // // public static Story fromNodeHNAPIStory(NodeHNAPIStory nodeHNAPIStory) { // return new Story(nodeHNAPIStory.id, // nodeHNAPIStory.title, // nodeHNAPIStory.url, // nodeHNAPIStory.domain, // nodeHNAPIStory.points, // nodeHNAPIStory.user, // nodeHNAPIStory.timeAgo, // nodeHNAPIStory.commentsCount, // nodeHNAPIStory.type); // } // // public Long getStoryId() { // return mStoryId; // } // // public String getTitle() { // return mTitle; // } // // public String getUrl() { // return mUrl; // } // // public String getDomain() { // return mDomain; // } // // public int getPoints() { // return mPoints; // } // // public String getSubmitter() { // return mSubmitter; // } // // public String getPublishedTime() { // return mPublishedTime; // } // // public int getNumComments() { // return mNumComments; // } // // public String getType() { // return mType; // } // // public void setStoryId(Long storyId) { // mStoryId = storyId; // } // // public void setTitle(String title) { // mTitle = title; // } // // public void setUrl(String url) { // mUrl = url; // } // // public void setDomain(String domain) { // mDomain = domain; // } // // public void setPoints(int points) { // mPoints = points; // } // // public void setSubmitter(String submitter) { // mSubmitter = submitter; // } // // public void setPublishedTime(String publishedTime) { // mPublishedTime = publishedTime; // } // // public void setNumComments(int numComments) { // mNumComments = numComments; // } // // public void setType(String type) { // mType = type; // } // // public boolean isSaved() { // return isSaved; // } // // public void setIsSaved(boolean isSaved) { // this.isSaved = isSaved; // } // // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Story story = (Story) o; // // if (mStoryId != null ? !mStoryId.equals(story.mStoryId) : story.mStoryId != null) // return false; // // return true; // } // // @Override // public int hashCode() { // return mStoryId != null ? mStoryId.hashCode() : 0; // } // // public boolean isRead() { // return mIsRead; // } // // public void setIsRead(boolean isRead) { // this.mIsRead = isRead; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeValue(this.mStoryId); // dest.writeString(this.mTitle); // dest.writeString(this.mUrl); // dest.writeString(this.mDomain); // dest.writeInt(this.mPoints); // dest.writeString(this.mSubmitter); // dest.writeString(this.mPublishedTime); // dest.writeInt(this.mNumComments); // dest.writeString(this.mType); // dest.writeByte(isSaved ? (byte) 1 : (byte) 0); // dest.writeByte(mIsRead ? (byte) 1 : (byte) 0); // } // // protected Story(Parcel in) { // this.mStoryId = (Long) in.readValue(Long.class.getClassLoader()); // this.mTitle = in.readString(); // this.mUrl = in.readString(); // this.mDomain = in.readString(); // this.mPoints = in.readInt(); // this.mSubmitter = in.readString(); // this.mPublishedTime = in.readString(); // this.mNumComments = in.readInt(); // this.mType = in.readString(); // this.isSaved = in.readByte() != 0; // this.mIsRead = in.readByte() != 0; // } // // public static final Creator<Story> CREATOR = new Creator<Story>() { // public Story createFromParcel(Parcel source) { // return new Story(source); // } // // public Story[] newArray(int size) { // return new Story[size]; // } // }; // } // Path: app/src/main/java/io/dwak/holohackernews/app/ui/storylist/StoryListAdapter.java import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.List; import io.dwak.holohackernews.app.models.Story; package io.dwak.holohackernews.app.ui.storylist; public class StoryListAdapter extends RecyclerView.Adapter<StoryViewHolder> { @NonNull private final Context mContext;
private final List<Story> mStoryList;
tsegismont/simone
src/test/java/org/rhq/simone/util/TickUtilTest.java
// Path: src/main/java/org/rhq/simone/util/TickUtil.java // public static long ticksToTimeUnit(long clockTicks, long ticksPerSecond, TimeUnit unit) { // switch (unit) { // case DAYS: // case HOURS: // case MINUTES: // return unit.convert(clockTicks / ticksPerSecond, SECONDS); // case SECONDS: // return clockTicks / ticksPerSecond; // case MILLISECONDS: // case MICROSECONDS: // case NANOSECONDS: // return unit.convert(1, SECONDS) * clockTicks / ticksPerSecond; // default: // throw new UnsupportedOperationException(String.valueOf(unit)); // } // }
import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static junit.framework.Assert.assertEquals; import static org.rhq.simone.util.TickUtil.ticksToTimeUnit; import org.junit.Test;
/* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.util; /** * @author Thomas Segismont */ public class TickUtilTest { @Test public void testTicksToTimeUnit() throws Exception { long ticksPerSecond = 87, clockTicks = ticksPerSecond * DAYS.toSeconds(1);
// Path: src/main/java/org/rhq/simone/util/TickUtil.java // public static long ticksToTimeUnit(long clockTicks, long ticksPerSecond, TimeUnit unit) { // switch (unit) { // case DAYS: // case HOURS: // case MINUTES: // return unit.convert(clockTicks / ticksPerSecond, SECONDS); // case SECONDS: // return clockTicks / ticksPerSecond; // case MILLISECONDS: // case MICROSECONDS: // case NANOSECONDS: // return unit.convert(1, SECONDS) * clockTicks / ticksPerSecond; // default: // throw new UnsupportedOperationException(String.valueOf(unit)); // } // } // Path: src/test/java/org/rhq/simone/util/TickUtilTest.java import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static junit.framework.Assert.assertEquals; import static org.rhq.simone.util.TickUtil.ticksToTimeUnit; import org.junit.Test; /* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.util; /** * @author Thomas Segismont */ public class TickUtilTest { @Test public void testTicksToTimeUnit() throws Exception { long ticksPerSecond = 87, clockTicks = ticksPerSecond * DAYS.toSeconds(1);
assertEquals(1, ticksToTimeUnit(clockTicks, ticksPerSecond, DAYS));
tsegismont/simone
src/main/java/org/rhq/simone/util/log/ConsoleLog.java
// Path: src/main/java/org/rhq/simone/util/ThrowableUtil.java // public static String throwableToString(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // }
import static org.rhq.simone.util.ThrowableUtil.throwableToString; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date;
println(System.out, Level.WARN, message); } @Override public void warn(String message, Throwable t) { println(System.out, Level.WARN, message, t); } @Override public void error(String message) { println(System.err, Level.ERROR, message); } @Override public void error(String message, Throwable t) { println(System.err, Level.ERROR, message, t); } private void println(PrintStream stream, Level level, String message) { println(stream, level, message, null); } private void println(PrintStream stream, Level level, String message, Throwable t) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz"); StringBuilder sb = new StringBuilder(sdf.format(new Date())).append(" [").append(level).append("] [").append(className) .append("] ").append(message); if (t != null) { sb.append(System.getProperty("line.separator"));
// Path: src/main/java/org/rhq/simone/util/ThrowableUtil.java // public static String throwableToString(Throwable t) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // Path: src/main/java/org/rhq/simone/util/log/ConsoleLog.java import static org.rhq.simone.util.ThrowableUtil.throwableToString; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; println(System.out, Level.WARN, message); } @Override public void warn(String message, Throwable t) { println(System.out, Level.WARN, message, t); } @Override public void error(String message) { println(System.err, Level.ERROR, message); } @Override public void error(String message, Throwable t) { println(System.err, Level.ERROR, message, t); } private void println(PrintStream stream, Level level, String message) { println(stream, level, message, null); } private void println(PrintStream stream, Level level, String message, Throwable t) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz"); StringBuilder sb = new StringBuilder(sdf.format(new Date())).append(" [").append(level).append("] [").append(className) .append("] ").append(message); if (t != null) { sb.append(System.getProperty("line.separator"));
sb.append(throwableToString(t));
tsegismont/simone
src/main/java/org/rhq/simone/cpu/linux/CpuDetailsParser.java
// Path: src/main/java/org/rhq/simone/util/IOUtil.java // public static void closeQuietly(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignore) { // } // } // } // // Path: src/main/java/org/rhq/simone/cpu/CpuDetails.java // public class CpuDetails { // // private final String vendorId; // private final String modelName; // private final int cpuFrequency; // private final int cacheSize; // // public CpuDetails(String vendorId, String modelName, int cpuFrequency, int cacheSize) { // this.vendorId = vendorId; // this.modelName = modelName; // this.cpuFrequency = cpuFrequency; // this.cacheSize = cacheSize; // } // // public String getVendorId() { // return vendorId; // } // // public String getModelName() { // return modelName; // } // // /** // * @return frequency in MHz // */ // public int getCpuFrequency() { // return cpuFrequency; // } // // /** // * @return cache size in kilobytes // */ // public int getCacheSize() { // return cacheSize; // } // // @Override // public String toString() { // return "CpuDetails[" + // "vendorId='" + vendorId + '\'' + // ", modelName='" + modelName + '\'' + // ", cpuFrequency(MHz)=" + cpuFrequency + // ", cacheSize(KB)=" + cacheSize + // ']'; // } // }
import static org.rhq.simone.util.IOUtil.closeQuietly; import org.rhq.simone.cpu.CpuDetails; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.util.Iterator;
/* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.cpu.linux; /** * @author Thomas Segismont */ class CpuDetailsParser implements Iterable<CpuDetails>, Closeable { private final BufferedReader bufferedReader; CpuDetailsParser(BufferedReader bufferedReader) { this.bufferedReader = bufferedReader; } @Override public Iterator<CpuDetails> iterator() { return new CpuDetailsIterator(bufferedReader); } @Override public void close() throws IOException {
// Path: src/main/java/org/rhq/simone/util/IOUtil.java // public static void closeQuietly(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignore) { // } // } // } // // Path: src/main/java/org/rhq/simone/cpu/CpuDetails.java // public class CpuDetails { // // private final String vendorId; // private final String modelName; // private final int cpuFrequency; // private final int cacheSize; // // public CpuDetails(String vendorId, String modelName, int cpuFrequency, int cacheSize) { // this.vendorId = vendorId; // this.modelName = modelName; // this.cpuFrequency = cpuFrequency; // this.cacheSize = cacheSize; // } // // public String getVendorId() { // return vendorId; // } // // public String getModelName() { // return modelName; // } // // /** // * @return frequency in MHz // */ // public int getCpuFrequency() { // return cpuFrequency; // } // // /** // * @return cache size in kilobytes // */ // public int getCacheSize() { // return cacheSize; // } // // @Override // public String toString() { // return "CpuDetails[" + // "vendorId='" + vendorId + '\'' + // ", modelName='" + modelName + '\'' + // ", cpuFrequency(MHz)=" + cpuFrequency + // ", cacheSize(KB)=" + cacheSize + // ']'; // } // } // Path: src/main/java/org/rhq/simone/cpu/linux/CpuDetailsParser.java import static org.rhq.simone.util.IOUtil.closeQuietly; import org.rhq.simone.cpu.CpuDetails; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; /* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.cpu.linux; /** * @author Thomas Segismont */ class CpuDetailsParser implements Iterable<CpuDetails>, Closeable { private final BufferedReader bufferedReader; CpuDetailsParser(BufferedReader bufferedReader) { this.bufferedReader = bufferedReader; } @Override public Iterator<CpuDetails> iterator() { return new CpuDetailsIterator(bufferedReader); } @Override public void close() throws IOException {
closeQuietly(bufferedReader);
tsegismont/simone
src/main/java/org/rhq/simone/system/SystemServiceFactory.java
// Path: src/main/java/org/rhq/simone/system/linux/LinuxSystemService.java // public class LinuxSystemService implements SystemService { // // private static final Log LOG = LogFactory.getLog(LinuxSystemService.class); // // public LinuxSystemService(POSIX posix) { // } // // @Override // public SystemLoad getSystemLoad() { // String uptimeLine = readFirstLine(new File("/proc/uptime")); // StringTokenizer uptimeTokenizer = new StringTokenizer(uptimeLine); // long upTime = new BigDecimal(uptimeTokenizer.nextToken()).setScale(0, HALF_EVEN).longValue(); // long idleTime = new BigDecimal(uptimeTokenizer.nextToken()).setScale(0, HALF_EVEN).longValue(); // String loadLine = readFirstLine(new File("/proc/loadavg")); // StringTokenizer loadLineTokenizer = new StringTokenizer(loadLine); // float load1Minute = parseFloat(loadLineTokenizer.nextToken()); // float load5Minutes = parseFloat(loadLineTokenizer.nextToken()); // float load15Minutes = parseFloat(loadLineTokenizer.nextToken()); // return new SystemLoad(upTime, idleTime, load1Minute, load5Minutes, load15Minutes); // } // // @Override // public SystemMemoryUsage getSystemMemoryUsage() { // Map<String, String> details = new HashMap<String, String>(); // for (String line : readLines(new File("/proc/meminfo"))) { // int separatorIndex = line.indexOf(":"); // if (separatorIndex <= 0 || separatorIndex == line.length() - 1) { // if (LOG.isDebugEnabled()) { // LOG.debug("Invalid detail line format: " + line); // } // continue; // } // details.put(line.substring(0, separatorIndex).trim(), line.substring(separatorIndex + 1).trim()); // } // long total = readSizeFromDetail(details.get("MemTotal"), KILOBYTES, KILOBYTES); // long free = readSizeFromDetail(details.get("MemFree"), KILOBYTES, KILOBYTES); // long active = readSizeFromDetail(details.get("Active"), KILOBYTES, KILOBYTES); // long inactive = readSizeFromDetail(details.get("Inactive"), KILOBYTES, KILOBYTES); // long swapTotal = readSizeFromDetail(details.get("SwapTotal"), KILOBYTES, KILOBYTES); // long swapFree = readSizeFromDetail(details.get("SwapFree"), KILOBYTES, KILOBYTES); // return new SystemMemoryUsage(total, free, active, inactive, swapTotal, swapFree); // } // // private long readSizeFromDetail(String detail, SizeUnit defaultUnit, SizeUnit targetUnit) { // StringTokenizer tokenizer = new StringTokenizer(detail); // long value = parseLong(tokenizer.nextToken()); // SizeUnit unit = tokenizer.hasMoreTokens() ? getSizeUnitFromString(tokenizer.nextToken()) : defaultUnit; // return targetUnit.convert(value, unit); // } // // private SizeUnit getSizeUnitFromString(String unitString) { // if ("kb".equalsIgnoreCase(unitString)) { // return KILOBYTES; // } // if ("mb".equalsIgnoreCase(unitString)) { // return MEGABYTES; // } // return BYTES; // } // // public static void main(String[] args) { // LinuxSystemService service = new LinuxSystemService(POSIXFactory.getPOSIX()); // System.out.println(service.getSystemLoad()); // System.out.println(service.getSystemMemoryUsage().toStringRatio()); // } // } // // Path: src/main/java/org/rhq/simone/util/log/Log.java // public interface Log { // // boolean isTraceEnabled(); // // void trace(String message); // // void trace(String message, Throwable t); // // boolean isDebugEnabled(); // // void debug(String message); // // void debug(String message, Throwable t); // // boolean isInfoEnabled(); // // void info(String message); // // void info(String message, Throwable t); // // boolean isWarnEnabled(); // // void warn(String message); // // void warn(String message, Throwable t); // // void error(String message); // // void error(String message, Throwable t); // } // // Path: src/main/java/org/rhq/simone/util/log/LogFactory.java // public class LogFactory { // // private LogFactory() { // // Factory // } // // public static Log getLog(Class clazz) { // return new ConsoleLog(clazz); // } // }
import static jnr.ffi.Platform.getNativePlatform; import jnr.ffi.Platform; import jnr.posix.POSIX; import jnr.posix.POSIXFactory; import org.rhq.simone.system.linux.LinuxSystemService; import org.rhq.simone.util.log.Log; import org.rhq.simone.util.log.LogFactory;
/* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.system; /** * @author Thomas Segismont */ public class SystemServiceFactory { private static final Log LOG = LogFactory.getLog(SystemServiceFactory.class); private SystemServiceFactory() { // Factory } public static SystemService createSystemService() { return createSystemService(POSIXFactory.getPOSIX()); } public static SystemService createSystemService(POSIX posix) { try { Platform.OS os = getNativePlatform().getOS(); switch (os) { case LINUX: return createLinuxSystemService(posix); default: return null; } } catch (Throwable t) { LOG.error("Failed to create SystemService", t); return null; } } public static SystemService createLinuxSystemService(POSIX posix) {
// Path: src/main/java/org/rhq/simone/system/linux/LinuxSystemService.java // public class LinuxSystemService implements SystemService { // // private static final Log LOG = LogFactory.getLog(LinuxSystemService.class); // // public LinuxSystemService(POSIX posix) { // } // // @Override // public SystemLoad getSystemLoad() { // String uptimeLine = readFirstLine(new File("/proc/uptime")); // StringTokenizer uptimeTokenizer = new StringTokenizer(uptimeLine); // long upTime = new BigDecimal(uptimeTokenizer.nextToken()).setScale(0, HALF_EVEN).longValue(); // long idleTime = new BigDecimal(uptimeTokenizer.nextToken()).setScale(0, HALF_EVEN).longValue(); // String loadLine = readFirstLine(new File("/proc/loadavg")); // StringTokenizer loadLineTokenizer = new StringTokenizer(loadLine); // float load1Minute = parseFloat(loadLineTokenizer.nextToken()); // float load5Minutes = parseFloat(loadLineTokenizer.nextToken()); // float load15Minutes = parseFloat(loadLineTokenizer.nextToken()); // return new SystemLoad(upTime, idleTime, load1Minute, load5Minutes, load15Minutes); // } // // @Override // public SystemMemoryUsage getSystemMemoryUsage() { // Map<String, String> details = new HashMap<String, String>(); // for (String line : readLines(new File("/proc/meminfo"))) { // int separatorIndex = line.indexOf(":"); // if (separatorIndex <= 0 || separatorIndex == line.length() - 1) { // if (LOG.isDebugEnabled()) { // LOG.debug("Invalid detail line format: " + line); // } // continue; // } // details.put(line.substring(0, separatorIndex).trim(), line.substring(separatorIndex + 1).trim()); // } // long total = readSizeFromDetail(details.get("MemTotal"), KILOBYTES, KILOBYTES); // long free = readSizeFromDetail(details.get("MemFree"), KILOBYTES, KILOBYTES); // long active = readSizeFromDetail(details.get("Active"), KILOBYTES, KILOBYTES); // long inactive = readSizeFromDetail(details.get("Inactive"), KILOBYTES, KILOBYTES); // long swapTotal = readSizeFromDetail(details.get("SwapTotal"), KILOBYTES, KILOBYTES); // long swapFree = readSizeFromDetail(details.get("SwapFree"), KILOBYTES, KILOBYTES); // return new SystemMemoryUsage(total, free, active, inactive, swapTotal, swapFree); // } // // private long readSizeFromDetail(String detail, SizeUnit defaultUnit, SizeUnit targetUnit) { // StringTokenizer tokenizer = new StringTokenizer(detail); // long value = parseLong(tokenizer.nextToken()); // SizeUnit unit = tokenizer.hasMoreTokens() ? getSizeUnitFromString(tokenizer.nextToken()) : defaultUnit; // return targetUnit.convert(value, unit); // } // // private SizeUnit getSizeUnitFromString(String unitString) { // if ("kb".equalsIgnoreCase(unitString)) { // return KILOBYTES; // } // if ("mb".equalsIgnoreCase(unitString)) { // return MEGABYTES; // } // return BYTES; // } // // public static void main(String[] args) { // LinuxSystemService service = new LinuxSystemService(POSIXFactory.getPOSIX()); // System.out.println(service.getSystemLoad()); // System.out.println(service.getSystemMemoryUsage().toStringRatio()); // } // } // // Path: src/main/java/org/rhq/simone/util/log/Log.java // public interface Log { // // boolean isTraceEnabled(); // // void trace(String message); // // void trace(String message, Throwable t); // // boolean isDebugEnabled(); // // void debug(String message); // // void debug(String message, Throwable t); // // boolean isInfoEnabled(); // // void info(String message); // // void info(String message, Throwable t); // // boolean isWarnEnabled(); // // void warn(String message); // // void warn(String message, Throwable t); // // void error(String message); // // void error(String message, Throwable t); // } // // Path: src/main/java/org/rhq/simone/util/log/LogFactory.java // public class LogFactory { // // private LogFactory() { // // Factory // } // // public static Log getLog(Class clazz) { // return new ConsoleLog(clazz); // } // } // Path: src/main/java/org/rhq/simone/system/SystemServiceFactory.java import static jnr.ffi.Platform.getNativePlatform; import jnr.ffi.Platform; import jnr.posix.POSIX; import jnr.posix.POSIXFactory; import org.rhq.simone.system.linux.LinuxSystemService; import org.rhq.simone.util.log.Log; import org.rhq.simone.util.log.LogFactory; /* * Copyright 2014 Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rhq.simone.system; /** * @author Thomas Segismont */ public class SystemServiceFactory { private static final Log LOG = LogFactory.getLog(SystemServiceFactory.class); private SystemServiceFactory() { // Factory } public static SystemService createSystemService() { return createSystemService(POSIXFactory.getPOSIX()); } public static SystemService createSystemService(POSIX posix) { try { Platform.OS os = getNativePlatform().getOS(); switch (os) { case LINUX: return createLinuxSystemService(posix); default: return null; } } catch (Throwable t) { LOG.error("Failed to create SystemService", t); return null; } } public static SystemService createLinuxSystemService(POSIX posix) {
return new LinuxSystemService(posix);
upnext/blekit-android
src/main/java/com/upnext/blekit/model/CurrentBeaconProximity.java
// Path: src/main/java/com/upnext/blekit/Proximity.java // public enum Proximity { // // /** // * Beacon is far // */ // FAR, // // /** // * Beacon is near // */ // NEAR, // // /** // * Beacon is immediate // */ // IMMEDIATE, // // /** // * Proximity of beacon is uknown // */ // UNKNOWN; // // // /** // * Matches beacon event to proximity value // * // * @param beaconEvent beacon event // * @return proximity // */ // public static Proximity fromBeaconEvent( BeaconEvent beaconEvent ) { // if( beaconEvent==null ) return UNKNOWN; // // switch (beaconEvent) { // case REGION_ENTER: return FAR; // case CAME_FAR: return FAR; // case CAME_NEAR: return NEAR; // case CAME_IMMEDIATE: return IMMEDIATE; // default: return UNKNOWN; // } // } // // }
import android.os.Parcel; import android.os.Parcelable; import com.upnext.blekit.Proximity;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.model; /** * Helper class for passing beacon with its proximity in bundles. * * @author Roman Wozniak ([email protected]) */ public class CurrentBeaconProximity implements Parcelable { private String beaconId;
// Path: src/main/java/com/upnext/blekit/Proximity.java // public enum Proximity { // // /** // * Beacon is far // */ // FAR, // // /** // * Beacon is near // */ // NEAR, // // /** // * Beacon is immediate // */ // IMMEDIATE, // // /** // * Proximity of beacon is uknown // */ // UNKNOWN; // // // /** // * Matches beacon event to proximity value // * // * @param beaconEvent beacon event // * @return proximity // */ // public static Proximity fromBeaconEvent( BeaconEvent beaconEvent ) { // if( beaconEvent==null ) return UNKNOWN; // // switch (beaconEvent) { // case REGION_ENTER: return FAR; // case CAME_FAR: return FAR; // case CAME_NEAR: return NEAR; // case CAME_IMMEDIATE: return IMMEDIATE; // default: return UNKNOWN; // } // } // // } // Path: src/main/java/com/upnext/blekit/model/CurrentBeaconProximity.java import android.os.Parcel; import android.os.Parcelable; import com.upnext.blekit.Proximity; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.model; /** * Helper class for passing beacon with its proximity in bundles. * * @author Roman Wozniak ([email protected]) */ public class CurrentBeaconProximity implements Parcelable { private String beaconId;
private Proximity proximity;
upnext/blekit-android
src/main/java/com/upnext/blekit/StartupReceiver.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.util.L;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit; /** * Receives a <code>android.intent.action.BOOT_COMPLETED</code> intent upon device boot and starts the service. * * @author Roman Wozniak ([email protected]) */ public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/StartupReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.util.L; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit; /** * Receives a <code>android.intent.action.BOOT_COMPLETED</code> intent upon device boot and starts the service. * * @author Roman Wozniak ([email protected]) */ public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
L.d(".");
upnext/blekit-android
src/main/java/com/upnext/blekit/listeners/BLEKitStateListener.java
// Path: src/main/java/com/upnext/blekit/Proximity.java // public enum Proximity { // // /** // * Beacon is far // */ // FAR, // // /** // * Beacon is near // */ // NEAR, // // /** // * Beacon is immediate // */ // IMMEDIATE, // // /** // * Proximity of beacon is uknown // */ // UNKNOWN; // // // /** // * Matches beacon event to proximity value // * // * @param beaconEvent beacon event // * @return proximity // */ // public static Proximity fromBeaconEvent( BeaconEvent beaconEvent ) { // if( beaconEvent==null ) return UNKNOWN; // // switch (beaconEvent) { // case REGION_ENTER: return FAR; // case CAME_FAR: return FAR; // case CAME_NEAR: return NEAR; // case CAME_IMMEDIATE: return IMMEDIATE; // default: return UNKNOWN; // } // } // // }
import com.upnext.blekit.Proximity;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.listeners; /** * Listener for BLEKit states - start and stop. * * @author Roman Wozniak ([email protected]) */ public interface BLEKitStateListener { /** * Called after BLEKit has successfully started. */ void onBLEKitStarted(); /** * Called after BLEKit has stopped. */ void onBLEKitStopped(); /** * Called after connecting to BLEKit service and getting current state of beacons * * @param beaconId beacon identifier * @param proximity beacon proximity */
// Path: src/main/java/com/upnext/blekit/Proximity.java // public enum Proximity { // // /** // * Beacon is far // */ // FAR, // // /** // * Beacon is near // */ // NEAR, // // /** // * Beacon is immediate // */ // IMMEDIATE, // // /** // * Proximity of beacon is uknown // */ // UNKNOWN; // // // /** // * Matches beacon event to proximity value // * // * @param beaconEvent beacon event // * @return proximity // */ // public static Proximity fromBeaconEvent( BeaconEvent beaconEvent ) { // if( beaconEvent==null ) return UNKNOWN; // // switch (beaconEvent) { // case REGION_ENTER: return FAR; // case CAME_FAR: return FAR; // case CAME_NEAR: return NEAR; // case CAME_IMMEDIATE: return IMMEDIATE; // default: return UNKNOWN; // } // } // // } // Path: src/main/java/com/upnext/blekit/listeners/BLEKitStateListener.java import com.upnext.blekit.Proximity; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.listeners; /** * Listener for BLEKit states - start and stop. * * @author Roman Wozniak ([email protected]) */ public interface BLEKitStateListener { /** * Called after BLEKit has successfully started. */ void onBLEKitStarted(); /** * Called after BLEKit has stopped. */ void onBLEKitStopped(); /** * Called after connecting to BLEKit service and getting current state of beacons * * @param beaconId beacon identifier * @param proximity beacon proximity */
void onCurrentBeaconProximityReceived( String beaconId, Proximity proximity );
upnext/blekit-android
src/main/java/com/upnext/blekit/BLEKitIntentProcessor.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import android.app.IntentService; import android.content.Intent; import com.upnext.blekit.util.L;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit; /** * Service for processing intent in destination app process. * It is called by BLEKit service when a beacon event is meant to be sent to target application. * * @author Roman Wozniak ([email protected]) */ public class BLEKitIntentProcessor extends IntentService { public BLEKitIntentProcessor() { super("BLEKitIntentProcessor"); } @Override protected void onHandleIntent(Intent intent) {
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/BLEKitIntentProcessor.java import android.app.IntentService; import android.content.Intent; import com.upnext.blekit.util.L; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit; /** * Service for processing intent in destination app process. * It is called by BLEKit service when a beacon event is meant to be sent to target application. * * @author Roman Wozniak ([email protected]) */ public class BLEKitIntentProcessor extends IntentService { public BLEKitIntentProcessor() { super("BLEKitIntentProcessor"); } @Override protected void onHandleIntent(Intent intent) {
L.d( getPackageName() );
upnext/blekit-android
src/main/java/com/upnext/blekit/util/ExpressionEvaluator.java
// Path: src/main/java/com/upnext/blekit/model/Zone.java // public class Zone { // // /** // * Zone identifier // */ // public String id; // // /** // * Zone name // */ // public String name; // // /** // * Zone TTL // */ // public long ttl; // // /** // * Zone radius // */ // public double radius; // // /** // * Zone location // */ // public Location location; // // /** // * Zone beacons // */ // public List<Beacon> beacons; // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return "Zone{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", ttl=" + ttl + // ", radius=" + radius + // ", location=" + location + // ", beacons=" + beacons + // '}'; // } // // /** // * Returns <code>true</code> if this zone contains a beacon that matches given Region. // * // * @param region region // * @return <code>true</code> if this zone contains a beacon that matches given Region, <code>false</code> otherwise // */ // public boolean containsMatchingBeacon( Region region ) { // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // return true; // } // return false; // } // // /** // * Returns a collection of beacons that match given region. // * If no beacons match, an empty collection is returned. // * // * @param region region // * @return collection of beacons // */ // public List<Beacon> getMatchingBeacons( Region region ) { // List<Beacon> matchingBeacons = new ArrayList<Beacon>(); // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // matchingBeacons.add(beacon); // } // return matchingBeacons; // } // }
import java.util.Map; import com.upnext.blekit.model.Zone; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * Class used for evaluating expressions in conditions {@link com.upnext.blekit.conditions.BLECondition#expression} * * @see com.upnext.blekit.conditions.BLECondition * @author Roman Wozniak ([email protected]) */ public class ExpressionEvaluator { private Scriptable scope; private Context ctx;
// Path: src/main/java/com/upnext/blekit/model/Zone.java // public class Zone { // // /** // * Zone identifier // */ // public String id; // // /** // * Zone name // */ // public String name; // // /** // * Zone TTL // */ // public long ttl; // // /** // * Zone radius // */ // public double radius; // // /** // * Zone location // */ // public Location location; // // /** // * Zone beacons // */ // public List<Beacon> beacons; // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return "Zone{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", ttl=" + ttl + // ", radius=" + radius + // ", location=" + location + // ", beacons=" + beacons + // '}'; // } // // /** // * Returns <code>true</code> if this zone contains a beacon that matches given Region. // * // * @param region region // * @return <code>true</code> if this zone contains a beacon that matches given Region, <code>false</code> otherwise // */ // public boolean containsMatchingBeacon( Region region ) { // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // return true; // } // return false; // } // // /** // * Returns a collection of beacons that match given region. // * If no beacons match, an empty collection is returned. // * // * @param region region // * @return collection of beacons // */ // public List<Beacon> getMatchingBeacons( Region region ) { // List<Beacon> matchingBeacons = new ArrayList<Beacon>(); // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // matchingBeacons.add(beacon); // } // return matchingBeacons; // } // } // Path: src/main/java/com/upnext/blekit/util/ExpressionEvaluator.java import java.util.Map; import com.upnext.blekit.model.Zone; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * Class used for evaluating expressions in conditions {@link com.upnext.blekit.conditions.BLECondition#expression} * * @see com.upnext.blekit.conditions.BLECondition * @author Roman Wozniak ([email protected]) */ public class ExpressionEvaluator { private Scriptable scope; private Context ctx;
private Zone zone;
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/OccurenceParams.java
// Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // }
import com.upnext.blekit.EventOccurenceUnit;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Parameters for {@link com.upnext.blekit.conditions.OccurenceCondition} * * @author Roman Wozniak ([email protected]) */ public class OccurenceParams { /** * Number of occurences in given unit of time. */ public Integer occurence; /** * Occurence unit, default value is {@link com.upnext.blekit.EventOccurenceUnit#TOTAL} */
// Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // } // Path: src/main/java/com/upnext/blekit/conditions/OccurenceParams.java import com.upnext.blekit.EventOccurenceUnit; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Parameters for {@link com.upnext.blekit.conditions.OccurenceCondition} * * @author Roman Wozniak ([email protected]) */ public class OccurenceParams { /** * Number of occurences in given unit of time. */ public Integer occurence; /** * Occurence unit, default value is {@link com.upnext.blekit.EventOccurenceUnit#TOTAL} */
public EventOccurenceUnit occurence_unit;
upnext/blekit-android
src/main/java/com/upnext/blekit/actions/NotificationAction.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import com.upnext.blekit.util.L;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.actions; /** * Action that sends an ordered broadcast. * Action of the broadcast is {@link #NOTIFICATION_ACTION}. * As an EXTRA String {@link #EXTRA_NAME} a parameter ({@link com.upnext.blekit.actions.NotificationActionParams#name}) value is passed. * * To receive this event set up a BroadcastRecevier in your AndroidManifest.xml: * <pre> * {@code * <receiver * android:name="com.your.package.name.MyNotificationReceiver" * android:enabled="true" * android:exported="true" > * <intent-filter android:priority="1" > * <action android:name="com.upnext.blekit.NOTIFICATION_ACTION"/> * </intent-filter> * </receiver> * } * </pre> * * Basic implememntation of that receiver would look like this: * <pre> * <code> * public class MyNotificationReceiver extends BroadcastReceiver { * * public MyNotificationReceiver() { * } * * {@literal @}Override * public void onReceive(Context context, Intent intent) { * if ( intent != null ) { * final String nameParam = intent.getStringExtra(NotificationAction.EXTRA_NAME); * //your code here * } * } * } * </code> * </pre> * * It is possible to cancel futher boradcast - {@link android.content.BroadcastReceiver#abortBroadcast()} * * @author Roman Wozniak ([email protected]) */ public class NotificationAction extends BLEAction<NotificationActionParams> { /** * Action name of the Intent */ public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; /** * Name of the EXTRA where parameter 'name' is passed */ public static final String EXTRA_NAME = "name"; public static final String TYPE = "notification"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override public Class<NotificationActionParams> getParameterClass() { return NotificationActionParams.class; } /** * Sends an ordered boradcast. * * @param context Android Context, passed from the calling entity */ @Override public void performInBackground(Context context) { sendBroadcast(context); } /** * Sends an ordered boradcast. * * @param activity activity on which behalf this action performs in foreground */ @Override public void performInForeground(Activity activity) { sendBroadcast(activity); } private void sendBroadcast( Context context ) {
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/actions/NotificationAction.java import android.app.Activity; import android.content.Context; import android.content.Intent; import com.upnext.blekit.util.L; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.actions; /** * Action that sends an ordered broadcast. * Action of the broadcast is {@link #NOTIFICATION_ACTION}. * As an EXTRA String {@link #EXTRA_NAME} a parameter ({@link com.upnext.blekit.actions.NotificationActionParams#name}) value is passed. * * To receive this event set up a BroadcastRecevier in your AndroidManifest.xml: * <pre> * {@code * <receiver * android:name="com.your.package.name.MyNotificationReceiver" * android:enabled="true" * android:exported="true" > * <intent-filter android:priority="1" > * <action android:name="com.upnext.blekit.NOTIFICATION_ACTION"/> * </intent-filter> * </receiver> * } * </pre> * * Basic implememntation of that receiver would look like this: * <pre> * <code> * public class MyNotificationReceiver extends BroadcastReceiver { * * public MyNotificationReceiver() { * } * * {@literal @}Override * public void onReceive(Context context, Intent intent) { * if ( intent != null ) { * final String nameParam = intent.getStringExtra(NotificationAction.EXTRA_NAME); * //your code here * } * } * } * </code> * </pre> * * It is possible to cancel futher boradcast - {@link android.content.BroadcastReceiver#abortBroadcast()} * * @author Roman Wozniak ([email protected]) */ public class NotificationAction extends BLEAction<NotificationActionParams> { /** * Action name of the Intent */ public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; /** * Name of the EXTRA where parameter 'name' is passed */ public static final String EXTRA_NAME = "name"; public static final String TYPE = "notification"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override public Class<NotificationActionParams> getParameterClass() { return NotificationActionParams.class; } /** * Sends an ordered boradcast. * * @param context Android Context, passed from the calling entity */ @Override public void performInBackground(Context context) { sendBroadcast(context); } /** * Sends an ordered boradcast. * * @param activity activity on which behalf this action performs in foreground */ @Override public void performInForeground(Activity activity) { sendBroadcast(activity); } private void sendBroadcast( Context context ) {
L.d( "sending " + parameters.name );
upnext/blekit-android
src/main/java/com/upnext/blekit/BLEKitClient.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.util.L; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable;
return inBackground; } public void setInBackground(boolean inBackground) { this.inBackground = inBackground; } public Set<String> getMonitoredBeaconIDs() { return monitoredBeaconIDs; } public void setMonitoredBeaconIDs(Set<String> monitoredBeaconIDs) { this.monitoredBeaconIDs = monitoredBeaconIDs; } public void setMonitoredBeaconIDs(List<String> monitoredBeaconIDs) { this.monitoredBeaconIDs = new HashSet<String>(); for( String id : monitoredBeaconIDs ) { this.monitoredBeaconIDs.add(id); } } /** * Sends an intent with beacon event to the application. * * @param context context * @param event beacon event * @param beaconId beacon that triggered the event */ public void call(Context context, BeaconEvent event, String beaconId) {
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/BLEKitClient.java import com.upnext.blekit.util.L; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable; return inBackground; } public void setInBackground(boolean inBackground) { this.inBackground = inBackground; } public Set<String> getMonitoredBeaconIDs() { return monitoredBeaconIDs; } public void setMonitoredBeaconIDs(Set<String> monitoredBeaconIDs) { this.monitoredBeaconIDs = monitoredBeaconIDs; } public void setMonitoredBeaconIDs(List<String> monitoredBeaconIDs) { this.monitoredBeaconIDs = new HashSet<String>(); for( String id : monitoredBeaconIDs ) { this.monitoredBeaconIDs.add(id); } } /** * Sends an intent with beacon event to the application. * * @param context context * @param event beacon event * @param beaconId beacon that triggered the event */ public void call(Context context, BeaconEvent event, String beaconId) {
L.d(". " + event + " " + beaconId);
upnext/blekit-android
src/main/java/com/upnext/blekit/util/BeaconsDB.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.EventOccurenceUnit; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * Local database used for storing BLEKit entities like events for counting their occurences. * * @author Roman Wozniak ([email protected]) */ public class BeaconsDB extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "BeaconsDB"; public BeaconsDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * {@inheritDoc} */ @Override public void onCreate(SQLiteDatabase db) { final String CREATE_BEACON_EVENTS_TABLE = "CREATE TABLE " + TABLE_BEACON_EVENTS + " ( " + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_EVENT + " TEXT, "+ KEY_BEACON_ID + " TEXT, "+ KEY_DATE + " INTEGER )"; db.execSQL(CREATE_BEACON_EVENTS_TABLE); } /** * {@inheritDoc} */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_BEACON_EVENTS); this.onCreate(db); } private static final String TABLE_BEACON_EVENTS = "beacon_events"; private static final String KEY_ID = "id"; private static final String KEY_EVENT = "event"; private static final String KEY_BEACON_ID = "beacon_id"; private static final String KEY_DATE = "date"; private static final String[] COLUMNS = {KEY_ID,KEY_EVENT,KEY_BEACON_ID,KEY_DATE}; /** * Adds an event to the events database * * @param event beacon event * @param beaconId beacon identifier */
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // } // Path: src/main/java/com/upnext/blekit/util/BeaconsDB.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.EventOccurenceUnit; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * Local database used for storing BLEKit entities like events for counting their occurences. * * @author Roman Wozniak ([email protected]) */ public class BeaconsDB extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "BeaconsDB"; public BeaconsDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * {@inheritDoc} */ @Override public void onCreate(SQLiteDatabase db) { final String CREATE_BEACON_EVENTS_TABLE = "CREATE TABLE " + TABLE_BEACON_EVENTS + " ( " + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_EVENT + " TEXT, "+ KEY_BEACON_ID + " TEXT, "+ KEY_DATE + " INTEGER )"; db.execSQL(CREATE_BEACON_EVENTS_TABLE); } /** * {@inheritDoc} */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_BEACON_EVENTS); this.onCreate(db); } private static final String TABLE_BEACON_EVENTS = "beacon_events"; private static final String KEY_ID = "id"; private static final String KEY_EVENT = "event"; private static final String KEY_BEACON_ID = "beacon_id"; private static final String KEY_DATE = "date"; private static final String[] COLUMNS = {KEY_ID,KEY_EVENT,KEY_BEACON_ID,KEY_DATE}; /** * Adds an event to the events database * * @param event beacon event * @param beaconId beacon identifier */
public void addBeaconEvent( BeaconEvent event, String beaconId ) {
upnext/blekit-android
src/main/java/com/upnext/blekit/util/BeaconsDB.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.EventOccurenceUnit; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;
private static final String KEY_BEACON_ID = "beacon_id"; private static final String KEY_DATE = "date"; private static final String[] COLUMNS = {KEY_ID,KEY_EVENT,KEY_BEACON_ID,KEY_DATE}; /** * Adds an event to the events database * * @param event beacon event * @param beaconId beacon identifier */ public void addBeaconEvent( BeaconEvent event, String beaconId ) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_EVENT, event.name()); values.put(KEY_BEACON_ID, beaconId); values.put(KEY_DATE, new Date().getTime()); db.insert(TABLE_BEACON_EVENTS, null, values); db.close(); } /** * Returns the number of occurences of event for given beacon id in unit of time. * * @param event beacon event * @param beaconId beacon id * @param occurenceUnit occurence unit * @return number of occurences */
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/EventOccurenceUnit.java // public enum EventOccurenceUnit { // // /** // * hour time unit // */ // HOUR, // // /** // * day time unit // */ // DAY, // // /** // * month time unit // */ // MONTH, // // /** // * year time unit // */ // YEAR, // // /** // * total time unit - all events are counted // */ // TOTAL; // // private static Map<String, EventOccurenceUnit> namesMap = new HashMap<String, EventOccurenceUnit>(5); // // static { // namesMap.put("hour", HOUR); // namesMap.put("day", DAY); // namesMap.put("month", MONTH); // namesMap.put("year", YEAR); // namesMap.put("total", TOTAL); // } // // @JsonCreator // public static EventOccurenceUnit forValue(String value) { // if( value==null ) return TOTAL; // EventOccurenceUnit event = namesMap.get(value.toLowerCase()); // if( event==null ) return TOTAL; // return event; // } // } // Path: src/main/java/com/upnext/blekit/util/BeaconsDB.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.EventOccurenceUnit; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; private static final String KEY_BEACON_ID = "beacon_id"; private static final String KEY_DATE = "date"; private static final String[] COLUMNS = {KEY_ID,KEY_EVENT,KEY_BEACON_ID,KEY_DATE}; /** * Adds an event to the events database * * @param event beacon event * @param beaconId beacon identifier */ public void addBeaconEvent( BeaconEvent event, String beaconId ) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_EVENT, event.name()); values.put(KEY_BEACON_ID, beaconId); values.put(KEY_DATE, new Date().getTime()); db.insert(TABLE_BEACON_EVENTS, null, values); db.close(); } /** * Returns the number of occurences of event for given beacon id in unit of time. * * @param event beacon event * @param beaconId beacon id * @param occurenceUnit occurence unit * @return number of occurences */
public int getNumOccurencesForBeaconInTime( BeaconEvent event, String beaconId, EventOccurenceUnit occurenceUnit ) {
upnext/blekit-android
src/main/java/com/upnext/blekit/util/http/HttpClient.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.util.L; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;
} try { String payloadString = objectMapper.writeValueAsString(payload); return fetchResponse(clazz, path, params, "POST", payloadString, "application/json;charset=UTF-8"); } catch (JsonProcessingException e) { return new Response<T>(Error.serlizerError(e)); } } public <T> Response<T> put(Class<T> clazz, String path, Map<String, String> params) { return fetchResponse(clazz, path, params, "PUT"); } public <T> Response<T> delete(Class<T> clazz, String path, Map<String, String> params) { return fetchResponse(clazz, path, params, "DELETE"); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod) { return fetchResponse(clazz, path, params, httpMethod, null); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload) { return fetchResponse(clazz, path, params, httpMethod, payload, "application/x-www-form-urlencoded;charset=UTF-8"); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try { String fullUrl = urlWithParams(path != null ? url + path : url, params);
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/util/http/HttpClient.java import com.upnext.blekit.util.L; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Map; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; } try { String payloadString = objectMapper.writeValueAsString(payload); return fetchResponse(clazz, path, params, "POST", payloadString, "application/json;charset=UTF-8"); } catch (JsonProcessingException e) { return new Response<T>(Error.serlizerError(e)); } } public <T> Response<T> put(Class<T> clazz, String path, Map<String, String> params) { return fetchResponse(clazz, path, params, "PUT"); } public <T> Response<T> delete(Class<T> clazz, String path, Map<String, String> params) { return fetchResponse(clazz, path, params, "DELETE"); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod) { return fetchResponse(clazz, path, params, httpMethod, null); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload) { return fetchResponse(clazz, path, params, httpMethod, payload, "application/x-www-form-urlencoded;charset=UTF-8"); } public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try { String fullUrl = urlWithParams(path != null ? url + path : url, params);
L.d("[" + httpMethod + "] " + fullUrl);
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/EnterCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.L;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#REGION_ENTER} has just been received. * * @author Roman Wozniak ([email protected]) */ public class EnterCondition extends OccurenceCondition { public static final String TYPE = "enter"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/conditions/EnterCondition.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.L; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#REGION_ENTER} has just been received. * * @author Roman Wozniak ([email protected]) */ public class EnterCondition extends OccurenceCondition { public static final String TYPE = "enter"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
return super.evaluate() && beaconEvent!=null && beaconEvent==BeaconEvent.REGION_ENTER;
upnext/blekit-android
src/main/java/com/upnext/blekit/util/JsonParser.java
// Path: src/main/java/com/upnext/blekit/model/Zone.java // public class Zone { // // /** // * Zone identifier // */ // public String id; // // /** // * Zone name // */ // public String name; // // /** // * Zone TTL // */ // public long ttl; // // /** // * Zone radius // */ // public double radius; // // /** // * Zone location // */ // public Location location; // // /** // * Zone beacons // */ // public List<Beacon> beacons; // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return "Zone{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", ttl=" + ttl + // ", radius=" + radius + // ", location=" + location + // ", beacons=" + beacons + // '}'; // } // // /** // * Returns <code>true</code> if this zone contains a beacon that matches given Region. // * // * @param region region // * @return <code>true</code> if this zone contains a beacon that matches given Region, <code>false</code> otherwise // */ // public boolean containsMatchingBeacon( Region region ) { // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // return true; // } // return false; // } // // /** // * Returns a collection of beacons that match given region. // * If no beacons match, an empty collection is returned. // * // * @param region region // * @return collection of beacons // */ // public List<Beacon> getMatchingBeacons( Region region ) { // List<Beacon> matchingBeacons = new ArrayList<Beacon>(); // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // matchingBeacons.add(beacon); // } // return matchingBeacons; // } // }
import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.upnext.blekit.model.Zone;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * JSON parser class, used to deserialize JSON into Objects. * * @author Roman Wozniak ([email protected]) */ public class JsonParser { private ObjectMapper objectMapper; /** * Constructor, initializes the obejct mapper, will not fail on unknown properties. */ public JsonParser() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } /** * Deserializes given JSON into {@link com.upnext.blekit.model.Zone} * * @param zoneJSON zone as plain JSON * @return zone as object */
// Path: src/main/java/com/upnext/blekit/model/Zone.java // public class Zone { // // /** // * Zone identifier // */ // public String id; // // /** // * Zone name // */ // public String name; // // /** // * Zone TTL // */ // public long ttl; // // /** // * Zone radius // */ // public double radius; // // /** // * Zone location // */ // public Location location; // // /** // * Zone beacons // */ // public List<Beacon> beacons; // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return "Zone{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", ttl=" + ttl + // ", radius=" + radius + // ", location=" + location + // ", beacons=" + beacons + // '}'; // } // // /** // * Returns <code>true</code> if this zone contains a beacon that matches given Region. // * // * @param region region // * @return <code>true</code> if this zone contains a beacon that matches given Region, <code>false</code> otherwise // */ // public boolean containsMatchingBeacon( Region region ) { // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // return true; // } // return false; // } // // /** // * Returns a collection of beacons that match given region. // * If no beacons match, an empty collection is returned. // * // * @param region region // * @return collection of beacons // */ // public List<Beacon> getMatchingBeacons( Region region ) { // List<Beacon> matchingBeacons = new ArrayList<Beacon>(); // for( Beacon beacon : beacons ) { // if( beacon.matchesRegion(region) ) // matchingBeacons.add(beacon); // } // return matchingBeacons; // } // } // Path: src/main/java/com/upnext/blekit/util/JsonParser.java import java.io.IOException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.upnext.blekit.model.Zone; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.util; /** * JSON parser class, used to deserialize JSON into Objects. * * @author Roman Wozniak ([email protected]) */ public class JsonParser { private ObjectMapper objectMapper; /** * Constructor, initializes the obejct mapper, will not fail on unknown properties. */ public JsonParser() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } /** * Deserializes given JSON into {@link com.upnext.blekit.model.Zone} * * @param zoneJSON zone as plain JSON * @return zone as object */
public Zone parse( String zoneJSON ) {
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/LeaveCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // }
import com.upnext.blekit.BeaconEvent;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#REGION_LEAVE} has just been received. * * @author Roman Wozniak ([email protected]) */ public class LeaveCondition extends OccurenceCondition { public static final String TYPE = "leave"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // Path: src/main/java/com/upnext/blekit/conditions/LeaveCondition.java import com.upnext.blekit.BeaconEvent; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#REGION_LEAVE} has just been received. * * @author Roman Wozniak ([email protected]) */ public class LeaveCondition extends OccurenceCondition { public static final String TYPE = "leave"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
return super.evaluate() && beaconEvent!=null && beaconEvent==BeaconEvent.REGION_LEAVE;
upnext/blekit-android
src/main/java/com/upnext/blekit/receiver/LoggingReceiver.java
// Path: src/main/java/com/upnext/blekit/actions/NotificationAction.java // public class NotificationAction extends BLEAction<NotificationActionParams> { // // /** // * Action name of the Intent // */ // public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; // // /** // * Name of the EXTRA where parameter 'name' is passed // */ // public static final String EXTRA_NAME = "name"; // // public static final String TYPE = "notification"; // // /** // * {@inheritDoc} // */ // @Override // public String getType() { // return TYPE; // } // // /** // * {@inheritDoc} // */ // @Override // public Class<NotificationActionParams> getParameterClass() { // return NotificationActionParams.class; // } // // /** // * Sends an ordered boradcast. // * // * @param context Android Context, passed from the calling entity // */ // @Override // public void performInBackground(Context context) { // sendBroadcast(context); // } // // /** // * Sends an ordered boradcast. // * // * @param activity activity on which behalf this action performs in foreground // */ // @Override // public void performInForeground(Activity activity) { // sendBroadcast(activity); // } // // private void sendBroadcast( Context context ) { // L.d( "sending " + parameters.name ); // Intent intent = new Intent(); // intent.setAction(NOTIFICATION_ACTION); // intent.putExtra( EXTRA_NAME, parameters.name ); // context.sendOrderedBroadcast(intent, null); // } // // /** // * Not used method. // * // * @param intent Intent // * @param activity Android Activity // */ // @Override // public void processIntent(Intent intent, Activity activity) { // //not used // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.util.L; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.actions.NotificationAction;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.receiver; /** * Sample receiver that logs notification events. * * @author Roman Wozniak ([email protected]) */ public class LoggingReceiver extends BroadcastReceiver { public LoggingReceiver() { } @Override public void onReceive(Context context, Intent intent) { String nameParam = null; if ( intent != null ) {
// Path: src/main/java/com/upnext/blekit/actions/NotificationAction.java // public class NotificationAction extends BLEAction<NotificationActionParams> { // // /** // * Action name of the Intent // */ // public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; // // /** // * Name of the EXTRA where parameter 'name' is passed // */ // public static final String EXTRA_NAME = "name"; // // public static final String TYPE = "notification"; // // /** // * {@inheritDoc} // */ // @Override // public String getType() { // return TYPE; // } // // /** // * {@inheritDoc} // */ // @Override // public Class<NotificationActionParams> getParameterClass() { // return NotificationActionParams.class; // } // // /** // * Sends an ordered boradcast. // * // * @param context Android Context, passed from the calling entity // */ // @Override // public void performInBackground(Context context) { // sendBroadcast(context); // } // // /** // * Sends an ordered boradcast. // * // * @param activity activity on which behalf this action performs in foreground // */ // @Override // public void performInForeground(Activity activity) { // sendBroadcast(activity); // } // // private void sendBroadcast( Context context ) { // L.d( "sending " + parameters.name ); // Intent intent = new Intent(); // intent.setAction(NOTIFICATION_ACTION); // intent.putExtra( EXTRA_NAME, parameters.name ); // context.sendOrderedBroadcast(intent, null); // } // // /** // * Not used method. // * // * @param intent Intent // * @param activity Android Activity // */ // @Override // public void processIntent(Intent intent, Activity activity) { // //not used // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/receiver/LoggingReceiver.java import com.upnext.blekit.util.L; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.actions.NotificationAction; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.receiver; /** * Sample receiver that logs notification events. * * @author Roman Wozniak ([email protected]) */ public class LoggingReceiver extends BroadcastReceiver { public LoggingReceiver() { } @Override public void onReceive(Context context, Intent intent) { String nameParam = null; if ( intent != null ) {
nameParam = intent.getStringExtra(NotificationAction.EXTRA_NAME);
upnext/blekit-android
src/main/java/com/upnext/blekit/receiver/LoggingReceiver.java
// Path: src/main/java/com/upnext/blekit/actions/NotificationAction.java // public class NotificationAction extends BLEAction<NotificationActionParams> { // // /** // * Action name of the Intent // */ // public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; // // /** // * Name of the EXTRA where parameter 'name' is passed // */ // public static final String EXTRA_NAME = "name"; // // public static final String TYPE = "notification"; // // /** // * {@inheritDoc} // */ // @Override // public String getType() { // return TYPE; // } // // /** // * {@inheritDoc} // */ // @Override // public Class<NotificationActionParams> getParameterClass() { // return NotificationActionParams.class; // } // // /** // * Sends an ordered boradcast. // * // * @param context Android Context, passed from the calling entity // */ // @Override // public void performInBackground(Context context) { // sendBroadcast(context); // } // // /** // * Sends an ordered boradcast. // * // * @param activity activity on which behalf this action performs in foreground // */ // @Override // public void performInForeground(Activity activity) { // sendBroadcast(activity); // } // // private void sendBroadcast( Context context ) { // L.d( "sending " + parameters.name ); // Intent intent = new Intent(); // intent.setAction(NOTIFICATION_ACTION); // intent.putExtra( EXTRA_NAME, parameters.name ); // context.sendOrderedBroadcast(intent, null); // } // // /** // * Not used method. // * // * @param intent Intent // * @param activity Android Activity // */ // @Override // public void processIntent(Intent intent, Activity activity) { // //not used // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.util.L; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.actions.NotificationAction;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.receiver; /** * Sample receiver that logs notification events. * * @author Roman Wozniak ([email protected]) */ public class LoggingReceiver extends BroadcastReceiver { public LoggingReceiver() { } @Override public void onReceive(Context context, Intent intent) { String nameParam = null; if ( intent != null ) { nameParam = intent.getStringExtra(NotificationAction.EXTRA_NAME); }
// Path: src/main/java/com/upnext/blekit/actions/NotificationAction.java // public class NotificationAction extends BLEAction<NotificationActionParams> { // // /** // * Action name of the Intent // */ // public static final String NOTIFICATION_ACTION = "com.upnext.blekit.NOTIFICATION_ACTION"; // // /** // * Name of the EXTRA where parameter 'name' is passed // */ // public static final String EXTRA_NAME = "name"; // // public static final String TYPE = "notification"; // // /** // * {@inheritDoc} // */ // @Override // public String getType() { // return TYPE; // } // // /** // * {@inheritDoc} // */ // @Override // public Class<NotificationActionParams> getParameterClass() { // return NotificationActionParams.class; // } // // /** // * Sends an ordered boradcast. // * // * @param context Android Context, passed from the calling entity // */ // @Override // public void performInBackground(Context context) { // sendBroadcast(context); // } // // /** // * Sends an ordered boradcast. // * // * @param activity activity on which behalf this action performs in foreground // */ // @Override // public void performInForeground(Activity activity) { // sendBroadcast(activity); // } // // private void sendBroadcast( Context context ) { // L.d( "sending " + parameters.name ); // Intent intent = new Intent(); // intent.setAction(NOTIFICATION_ACTION); // intent.putExtra( EXTRA_NAME, parameters.name ); // context.sendOrderedBroadcast(intent, null); // } // // /** // * Not used method. // * // * @param intent Intent // * @param activity Android Activity // */ // @Override // public void processIntent(Intent intent, Activity activity) { // //not used // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/receiver/LoggingReceiver.java import com.upnext.blekit.util.L; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.upnext.blekit.actions.NotificationAction; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.receiver; /** * Sample receiver that logs notification events. * * @author Roman Wozniak ([email protected]) */ public class LoggingReceiver extends BroadcastReceiver { public LoggingReceiver() { } @Override public void onReceive(Context context, Intent intent) { String nameParam = null; if ( intent != null ) { nameParam = intent.getStringExtra(NotificationAction.EXTRA_NAME); }
L.d( "BROADCAST RECEIVED: name=" + nameParam!=null ? nameParam : "(NULL value)" );
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/CameImmediateCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // }
import com.upnext.blekit.BeaconEvent;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_IMMEDIATE} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameImmediateCondition extends BLECondition<Void> { public static final String TYPE = "cameImmediate"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // Path: src/main/java/com/upnext/blekit/conditions/CameImmediateCondition.java import com.upnext.blekit.BeaconEvent; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_IMMEDIATE} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameImmediateCondition extends BLECondition<Void> { public static final String TYPE = "cameImmediate"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
return beaconEvent!=null && beaconEvent==BeaconEvent.CAME_IMMEDIATE;
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/CameNearCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.L;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_NEAR} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameNearCondition extends BLECondition<Void> { public static final String TYPE = "cameNear"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/conditions/CameNearCondition.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.L; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_NEAR} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameNearCondition extends BLECondition<Void> { public static final String TYPE = "cameNear"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
return beaconEvent!=null && beaconEvent==BeaconEvent.CAME_NEAR;
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/HttpOkCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/http/HttpUtils.java // public class HttpUtils { // // /** // * Checks whether there is a valid Internet connection available on the device. // * // * @param ctx Android Context, passed from the calling entity // * @return <code>true</code> if device is online // */ // public static boolean isOnline( Context ctx ) { // if( ctx==null ) return false; // ConnectivityManager connectivityManager // = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // /** // * Checks whether a HTTP GET request for given url returns HTTP OK (200) response. // * // * @param url url // * @param params optional HTTP params // * @return <code>true</code> if HTTP OK received, <code>false</code> otherwise // */ // public static boolean isHttpOk( String url, Map<String, String> params ) { // HttpClient client = new HttpClient( url ); // Response<Void> response = client.get( Void.class, params ); // return response!=null && !response.hasError(); // } // // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.http.HttpUtils; import java.util.HashMap; import java.util.Map;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Performs an HTTP GET call to given url with optional username parameter. * Condition is met only if HTTP response code 200 was returned. * * @author Roman Wozniak ([email protected]) */ public class HttpOkCondition extends BLECondition<HttpOkParams> { public static final String TYPE = "httpOk"; private static final String PARAM_USERNAME = "username"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/http/HttpUtils.java // public class HttpUtils { // // /** // * Checks whether there is a valid Internet connection available on the device. // * // * @param ctx Android Context, passed from the calling entity // * @return <code>true</code> if device is online // */ // public static boolean isOnline( Context ctx ) { // if( ctx==null ) return false; // ConnectivityManager connectivityManager // = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // /** // * Checks whether a HTTP GET request for given url returns HTTP OK (200) response. // * // * @param url url // * @param params optional HTTP params // * @return <code>true</code> if HTTP OK received, <code>false</code> otherwise // */ // public static boolean isHttpOk( String url, Map<String, String> params ) { // HttpClient client = new HttpClient( url ); // Response<Void> response = client.get( Void.class, params ); // return response!=null && !response.hasError(); // } // // } // Path: src/main/java/com/upnext/blekit/conditions/HttpOkCondition.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.http.HttpUtils; import java.util.HashMap; import java.util.Map; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Performs an HTTP GET call to given url with optional username parameter. * Condition is met only if HTTP response code 200 was returned. * * @author Roman Wozniak ([email protected]) */ public class HttpOkCondition extends BLECondition<HttpOkParams> { public static final String TYPE = "httpOk"; private static final String PARAM_USERNAME = "username"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
if( HttpUtils.isOnline(context) ) {
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/HttpOkCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/http/HttpUtils.java // public class HttpUtils { // // /** // * Checks whether there is a valid Internet connection available on the device. // * // * @param ctx Android Context, passed from the calling entity // * @return <code>true</code> if device is online // */ // public static boolean isOnline( Context ctx ) { // if( ctx==null ) return false; // ConnectivityManager connectivityManager // = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // /** // * Checks whether a HTTP GET request for given url returns HTTP OK (200) response. // * // * @param url url // * @param params optional HTTP params // * @return <code>true</code> if HTTP OK received, <code>false</code> otherwise // */ // public static boolean isHttpOk( String url, Map<String, String> params ) { // HttpClient client = new HttpClient( url ); // Response<Void> response = client.get( Void.class, params ); // return response!=null && !response.hasError(); // } // // }
import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.http.HttpUtils; import java.util.HashMap; import java.util.Map;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Performs an HTTP GET call to given url with optional username parameter. * Condition is met only if HTTP response code 200 was returned. * * @author Roman Wozniak ([email protected]) */ public class HttpOkCondition extends BLECondition<HttpOkParams> { public static final String TYPE = "httpOk"; private static final String PARAM_USERNAME = "username"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() { if( HttpUtils.isOnline(context) ) { Map<String, String> params = new HashMap<String, String>(); if( parameters.username!=null ) { params.put( PARAM_USERNAME, parameters.username ); } return HttpUtils.isHttpOk( parameters.url, params ); } return false; } /** * {@inheritDoc} */ @Override public Class<HttpOkParams> getParameterClass() { return HttpOkParams.class; } /** * Always valid. * * @param beaconEvent event * @return returns <code>true</code> */ @Override
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // // Path: src/main/java/com/upnext/blekit/util/http/HttpUtils.java // public class HttpUtils { // // /** // * Checks whether there is a valid Internet connection available on the device. // * // * @param ctx Android Context, passed from the calling entity // * @return <code>true</code> if device is online // */ // public static boolean isOnline( Context ctx ) { // if( ctx==null ) return false; // ConnectivityManager connectivityManager // = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); // return activeNetworkInfo != null && activeNetworkInfo.isConnected(); // } // // /** // * Checks whether a HTTP GET request for given url returns HTTP OK (200) response. // * // * @param url url // * @param params optional HTTP params // * @return <code>true</code> if HTTP OK received, <code>false</code> otherwise // */ // public static boolean isHttpOk( String url, Map<String, String> params ) { // HttpClient client = new HttpClient( url ); // Response<Void> response = client.get( Void.class, params ); // return response!=null && !response.hasError(); // } // // } // Path: src/main/java/com/upnext/blekit/conditions/HttpOkCondition.java import com.upnext.blekit.BeaconEvent; import com.upnext.blekit.util.http.HttpUtils; import java.util.HashMap; import java.util.Map; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Performs an HTTP GET call to given url with optional username parameter. * Condition is met only if HTTP response code 200 was returned. * * @author Roman Wozniak ([email protected]) */ public class HttpOkCondition extends BLECondition<HttpOkParams> { public static final String TYPE = "httpOk"; private static final String PARAM_USERNAME = "username"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() { if( HttpUtils.isOnline(context) ) { Map<String, String> params = new HashMap<String, String>(); if( parameters.username!=null ) { params.put( PARAM_USERNAME, parameters.username ); } return HttpUtils.isHttpOk( parameters.url, params ); } return false; } /** * {@inheritDoc} */ @Override public Class<HttpOkParams> getParameterClass() { return HttpOkParams.class; } /** * Always valid. * * @param beaconEvent event * @return returns <code>true</code> */ @Override
public boolean isValidForEvent(BeaconEvent beaconEvent) {
upnext/blekit-android
src/main/java/com/upnext/blekit/actions/facebook/FacebookCheckinActivity.java
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // }
import com.facebook.HttpMethod; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionDefaultAudience; import com.facebook.SessionLoginBehavior; import com.facebook.SessionState; import com.upnext.blekit.util.L; import java.util.Arrays; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.actions.facebook; /** * Helper Activity for logging in to Facebook. * * @author Roman Wozniak ([email protected]) */ public class FacebookCheckinActivity extends Activity { private String placeId; private String postMessage; private String privacy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( getIntent()!=null ) { placeId = getIntent().getStringExtra("place_id"); postMessage = getIntent().getStringExtra("post_message"); privacy = getIntent().getStringExtra("privacy"); }
// Path: src/main/java/com/upnext/blekit/util/L.java // public class L { // // /** // * Set to true if you want to see debug messages associated with this library // */ // public static final boolean DEBUG_ENABLED = false; // // private static final String APP_NAME = "BLEKIT"; // // public static void d( String msg ) { // debug( msg ); // } // // public static void d( Object obj ) { // if( obj != null ) // debug( obj.toString() ); // } // // public static void e( String msg ) { // Log.e(APP_NAME, msg); // } // // public static void e( String msg, Exception e ) { // Log.e( APP_NAME, msg, e ); // } // // private static void debug( String msg ) { // if( DEBUG_ENABLED ) { // StackTraceElement[] els = Thread.currentThread().getStackTrace(); // String className = els[4].getClassName(); // className = className.substring( className.lastIndexOf( "." )+1 ); // Log.d( APP_NAME, "[" + className + "." + els[4].getMethodName() + "] " + msg ); // } // } // // } // Path: src/main/java/com/upnext/blekit/actions/facebook/FacebookCheckinActivity.java import com.facebook.HttpMethod; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionDefaultAudience; import com.facebook.SessionLoginBehavior; import com.facebook.SessionState; import com.upnext.blekit.util.L; import java.util.Arrays; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.actions.facebook; /** * Helper Activity for logging in to Facebook. * * @author Roman Wozniak ([email protected]) */ public class FacebookCheckinActivity extends Activity { private String placeId; private String postMessage; private String privacy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( getIntent()!=null ) { placeId = getIntent().getStringExtra("place_id"); postMessage = getIntent().getStringExtra("post_message"); privacy = getIntent().getStringExtra("privacy"); }
L.d( "place_id= " + placeId );
upnext/blekit-android
src/main/java/com/upnext/blekit/conditions/CameFarCondition.java
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // }
import com.upnext.blekit.BeaconEvent;
/* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_FAR} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameFarCondition extends BLECondition<Void> { public static final String TYPE = "cameFar"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
// Path: src/main/java/com/upnext/blekit/BeaconEvent.java // public enum BeaconEvent { // // /** // * A beacon has appeared in range // */ // REGION_ENTER, // // /** // * A beacon has disappeared from range. // * This event is in reality delayed to prevent imemdiate enter-exit-enter events. // * Because of that LEAVE is delayed by {@link com.upnext.blekit.BLEKitService#LEAVE_MSG_DELAY_MILLIS} ms. // */ // REGION_LEAVE, // // /** // * A beacon has just changed proximity to immediate // */ // CAME_IMMEDIATE, // // /** // * A beacon has just changed proximity to near // */ // CAME_NEAR, // // /** // * A beacon has just changed proximity to far // */ // CAME_FAR; // // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param iBeacon ibeacon // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(IBeacon iBeacon) { // return fromIBeaconProximity(iBeacon.getProximity()); // } // // /** // * Matches IBeacon proximity to BeaconEvent proximity change // * // * @param proximity proximity // * @return beacon event // */ // public static BeaconEvent fromIBeaconProximity(int proximity) { // switch (proximity) { // case IBeacon.PROXIMITY_IMMEDIATE: // return CAME_IMMEDIATE; // // case IBeacon.PROXIMITY_NEAR: // return CAME_NEAR; // // case IBeacon.PROXIMITY_FAR: // return CAME_FAR; // // default: // return null; // } // } // } // Path: src/main/java/com/upnext/blekit/conditions/CameFarCondition.java import com.upnext.blekit.BeaconEvent; /* * Copyright (c) 2014 UP-NEXT. All rights reserved. * http://www.up-next.com * * 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 com.upnext.blekit.conditions; /** * Condition checking whether an {@link com.upnext.blekit.BeaconEvent#CAME_FAR} has just been received. * * @author Roman Wozniak ([email protected]) */ public class CameFarCondition extends BLECondition<Void> { public static final String TYPE = "cameFar"; /** * {@inheritDoc} */ @Override public String getType() { return TYPE; } /** * {@inheritDoc} */ @Override protected boolean evaluate() {
return beaconEvent!=null && beaconEvent==BeaconEvent.CAME_FAR;
HubSpot/Rosetta
RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // }
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean;
package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // } // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean; package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() {
WireSafeBean bean = new WireSafeBean();
HubSpot/Rosetta
RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // }
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean;
package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() { WireSafeBean bean = new WireSafeBean();
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // } // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean; package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() { WireSafeBean bean = new WireSafeBean();
bean.setSimple(WireSafeEnum.of(SimpleEnum.ONE));
HubSpot/Rosetta
RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // }
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean;
package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() { WireSafeBean bean = new WireSafeBean(); bean.setSimple(WireSafeEnum.of(SimpleEnum.ONE));
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/CustomEnum.java // public enum CustomEnum { // ONE(1), // TWO(2), // ; // // private static final Map<Integer, CustomEnum> LOOKUP = // Maps.uniqueIndex( // Arrays.asList(CustomEnum.values()), // CustomEnum::getValue); // // private final int value; // // CustomEnum(int value) { // this.value = value; // } // // @RosettaValue // public int getValue() { // return value; // } // // @RosettaCreator // public static CustomEnum from(int value) { // return Optional.ofNullable(LOOKUP.get(value)) // .orElseThrow(() -> new IllegalArgumentException("No enum for value: " + value)); // } // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/SimpleEnum.java // public enum SimpleEnum { // ONE, // TWO // } // // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/beans/WireSafeBean.java // public class WireSafeBean { // private WireSafeEnum<SimpleEnum> simple; // private WireSafeEnum<CustomEnum> custom; // // public WireSafeEnum<SimpleEnum> getSimple() { // return simple; // } // // public WireSafeEnum<CustomEnum> getCustom() { // return custom; // } // // public void setSimple(WireSafeEnum<SimpleEnum> simple) { // this.simple = simple; // } // // public void setCustom(WireSafeEnum<CustomEnum> custom) { // this.custom = custom; // } // // @Override // public String toString() { // return MoreObjects // .toStringHelper(WireSafeBean.class) // .add("simple", simple) // .add("custom", custom).toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // WireSafeBean bean = (WireSafeBean) o; // return Objects.equal(simple, bean.simple) && // Objects.equal(custom, bean.custom); // } // // @Override // public int hashCode() { // return Objects.hashCode(simple, custom); // } // } // Path: RosettaImmutables/src/test/java/com/hubspot/rosetta/immutables/WireSafeEnumTest.java import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.immutables.utils.WireSafeEnum; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.immutables.beans.CustomEnum; import com.hubspot.rosetta.immutables.beans.SimpleEnum; import com.hubspot.rosetta.immutables.beans.WireSafeBean; package com.hubspot.rosetta.immutables; public class WireSafeEnumTest { private static final ObjectMapper MAPPER = Rosetta .getMapper() .copy() .registerModule(new RosettaImmutablesModule()); @Test public void itCanSerializeBeanWithWireSafeField() { WireSafeBean bean = new WireSafeBean(); bean.setSimple(WireSafeEnum.of(SimpleEnum.ONE));
bean.setCustom(WireSafeEnum.of(CustomEnum.ONE));
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaNamingTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaNamingBean.java // @RosettaNaming(LowerCaseWithUnderscoresStrategy.class) // public class RosettaNamingBean { // private String stringProperty; // // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaNamingBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaNamingTest { private static final String JSON = "{\"string_property\":\"value\"}"; @Test public void itWritesUnderscoreJson() throws JsonProcessingException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaNamingBean.java // @RosettaNaming(LowerCaseWithUnderscoresStrategy.class) // public class RosettaNamingBean { // private String stringProperty; // // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaNamingTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaNamingBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaNamingTest { private static final String JSON = "{\"string_property\":\"value\"}"; @Test public void itWritesUnderscoreJson() throws JsonProcessingException {
RosettaNamingBean bean = new RosettaNamingBean();
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaNamingTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaNamingBean.java // @RosettaNaming(LowerCaseWithUnderscoresStrategy.class) // public class RosettaNamingBean { // private String stringProperty; // // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaNamingBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaNamingTest { private static final String JSON = "{\"string_property\":\"value\"}"; @Test public void itWritesUnderscoreJson() throws JsonProcessingException { RosettaNamingBean bean = new RosettaNamingBean(); bean.setStringProperty("value");
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaNamingBean.java // @RosettaNaming(LowerCaseWithUnderscoresStrategy.class) // public class RosettaNamingBean { // private String stringProperty; // // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaNamingTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaNamingBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaNamingTest { private static final String JSON = "{\"string_property\":\"value\"}"; @Test public void itWritesUnderscoreJson() throws JsonProcessingException { RosettaNamingBean bean = new RosettaNamingBean(); bean.setStringProperty("value");
assertThat(Rosetta.getMapper().writeValueAsString(bean)).isEqualTo(JSON);
HubSpot/Rosetta
RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaObjectMapper.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import org.jdbi.v3.core.config.JdbiConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule;
package com.hubspot.rosetta.jdbi3; public class RosettaObjectMapper implements JdbiConfig<RosettaObjectMapper> { private ObjectMapper objectMapper; public RosettaObjectMapper() {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaObjectMapper.java import org.jdbi.v3.core.config.JdbiConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule; package com.hubspot.rosetta.jdbi3; public class RosettaObjectMapper implements JdbiConfig<RosettaObjectMapper> { private ObjectMapper objectMapper; public RosettaObjectMapper() {
this(Rosetta.getMapper());
HubSpot/Rosetta
RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaObjectMapper.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import org.jdbi.v3.core.config.JdbiConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule;
package com.hubspot.rosetta.jdbi3; public class RosettaObjectMapper implements JdbiConfig<RosettaObjectMapper> { private ObjectMapper objectMapper; public RosettaObjectMapper() { this(Rosetta.getMapper()); } private RosettaObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public ObjectMapper getObjectMapper() { return objectMapper; } public void setObjectMapper(ObjectMapper objectMapper) {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaObjectMapper.java import org.jdbi.v3.core.config.JdbiConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule; package com.hubspot.rosetta.jdbi3; public class RosettaObjectMapper implements JdbiConfig<RosettaObjectMapper> { private ObjectMapper objectMapper; public RosettaObjectMapper() { this(Rosetta.getMapper()); } private RosettaObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } public ObjectMapper getObjectMapper() { return objectMapper; } public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper.copy().registerModule(new RosettaModule());
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaPropertyTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaPropertyBean.java // public class RosettaPropertyBean { // @RosettaProperty("mccartney_song_title") // private String mcCartneySongTitle; // // @RosettaProperty // @JsonIgnore // private String jsonIgnoreRosettaUse; // // public String getMcCartneySongTitle() { // return mcCartneySongTitle; // } // // public RosettaPropertyBean setMcCartneySongTitle(String mcCartneySongTitle) { // this.mcCartneySongTitle = mcCartneySongTitle; // return this; // } // // public String getJsonIgnoreRosettaUse() { // return jsonIgnoreRosettaUse; // } // // public RosettaPropertyBean setJsonIgnoreRosettaUse(String jsonIgnoreRosettaUse) { // this.jsonIgnoreRosettaUse = jsonIgnoreRosettaUse; // return this; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaPropertyBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaPropertyTest { private static final String JSON = "{\"jsonIgnoreRosettaUse\":\"Here\",\"mccartney_song_title\":\"Hey Jude\"}"; private static final String JACKSON_JSON = "{\"mcCartneySongTitle\":\"Hey Jude\"}"; @Test public void itWritesWithThePropertyName() throws JsonProcessingException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaPropertyBean.java // public class RosettaPropertyBean { // @RosettaProperty("mccartney_song_title") // private String mcCartneySongTitle; // // @RosettaProperty // @JsonIgnore // private String jsonIgnoreRosettaUse; // // public String getMcCartneySongTitle() { // return mcCartneySongTitle; // } // // public RosettaPropertyBean setMcCartneySongTitle(String mcCartneySongTitle) { // this.mcCartneySongTitle = mcCartneySongTitle; // return this; // } // // public String getJsonIgnoreRosettaUse() { // return jsonIgnoreRosettaUse; // } // // public RosettaPropertyBean setJsonIgnoreRosettaUse(String jsonIgnoreRosettaUse) { // this.jsonIgnoreRosettaUse = jsonIgnoreRosettaUse; // return this; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaPropertyTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaPropertyBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaPropertyTest { private static final String JSON = "{\"jsonIgnoreRosettaUse\":\"Here\",\"mccartney_song_title\":\"Hey Jude\"}"; private static final String JACKSON_JSON = "{\"mcCartneySongTitle\":\"Hey Jude\"}"; @Test public void itWritesWithThePropertyName() throws JsonProcessingException {
RosettaPropertyBean bean = new RosettaPropertyBean();
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaPropertyTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaPropertyBean.java // public class RosettaPropertyBean { // @RosettaProperty("mccartney_song_title") // private String mcCartneySongTitle; // // @RosettaProperty // @JsonIgnore // private String jsonIgnoreRosettaUse; // // public String getMcCartneySongTitle() { // return mcCartneySongTitle; // } // // public RosettaPropertyBean setMcCartneySongTitle(String mcCartneySongTitle) { // this.mcCartneySongTitle = mcCartneySongTitle; // return this; // } // // public String getJsonIgnoreRosettaUse() { // return jsonIgnoreRosettaUse; // } // // public RosettaPropertyBean setJsonIgnoreRosettaUse(String jsonIgnoreRosettaUse) { // this.jsonIgnoreRosettaUse = jsonIgnoreRosettaUse; // return this; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaPropertyBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaPropertyTest { private static final String JSON = "{\"jsonIgnoreRosettaUse\":\"Here\",\"mccartney_song_title\":\"Hey Jude\"}"; private static final String JACKSON_JSON = "{\"mcCartneySongTitle\":\"Hey Jude\"}"; @Test public void itWritesWithThePropertyName() throws JsonProcessingException { RosettaPropertyBean bean = new RosettaPropertyBean(); bean.setMcCartneySongTitle("Hey Jude"); bean.setJsonIgnoreRosettaUse("Here");
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaPropertyBean.java // public class RosettaPropertyBean { // @RosettaProperty("mccartney_song_title") // private String mcCartneySongTitle; // // @RosettaProperty // @JsonIgnore // private String jsonIgnoreRosettaUse; // // public String getMcCartneySongTitle() { // return mcCartneySongTitle; // } // // public RosettaPropertyBean setMcCartneySongTitle(String mcCartneySongTitle) { // this.mcCartneySongTitle = mcCartneySongTitle; // return this; // } // // public String getJsonIgnoreRosettaUse() { // return jsonIgnoreRosettaUse; // } // // public RosettaPropertyBean setJsonIgnoreRosettaUse(String jsonIgnoreRosettaUse) { // this.jsonIgnoreRosettaUse = jsonIgnoreRosettaUse; // return this; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaPropertyTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaPropertyBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaPropertyTest { private static final String JSON = "{\"jsonIgnoreRosettaUse\":\"Here\",\"mccartney_song_title\":\"Hey Jude\"}"; private static final String JACKSON_JSON = "{\"mcCartneySongTitle\":\"Hey Jude\"}"; @Test public void itWritesWithThePropertyName() throws JsonProcessingException { RosettaPropertyBean bean = new RosettaPropertyBean(); bean.setMcCartneySongTitle("Hey Jude"); bean.setJsonIgnoreRosettaUse("Here");
assertThat(Rosetta.getMapper().writeValueAsString(bean)).isEqualTo(JSON);
HubSpot/Rosetta
RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaRowMapperFactory.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // }
import java.lang.reflect.Type; import java.util.Optional; import org.jdbi.v3.core.config.ConfigRegistry; import org.jdbi.v3.core.generic.GenericTypes; import org.jdbi.v3.core.mapper.ColumnMappers; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.mapper.RowMapperFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor;
package com.hubspot.rosetta.jdbi3; public class RosettaRowMapperFactory implements RowMapperFactory { @Override public Optional<RowMapper<?>> build(Type type, ConfigRegistry config) { if (accepts(type, config)) { return Optional.of((rs, ctx) -> { ObjectMapper objectMapper = ctx.getConfig(RosettaObjectMapper.class).getObjectMapper();
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // } // Path: RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaRowMapperFactory.java import java.lang.reflect.Type; import java.util.Optional; import org.jdbi.v3.core.config.ConfigRegistry; import org.jdbi.v3.core.generic.GenericTypes; import org.jdbi.v3.core.mapper.ColumnMappers; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.mapper.RowMapperFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor; package com.hubspot.rosetta.jdbi3; public class RosettaRowMapperFactory implements RowMapperFactory { @Override public Optional<RowMapper<?>> build(Type type, ConfigRegistry config) { if (accepts(type, config)) { return Optional.of((rs, ctx) -> { ObjectMapper objectMapper = ctx.getConfig(RosettaObjectMapper.class).getObjectMapper();
String tableName = SqlTableNameExtractor.extractTableName(ctx.getParsedSql().getSql());
HubSpot/Rosetta
RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaRowMapperFactory.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // }
import java.lang.reflect.Type; import java.util.Optional; import org.jdbi.v3.core.config.ConfigRegistry; import org.jdbi.v3.core.generic.GenericTypes; import org.jdbi.v3.core.mapper.ColumnMappers; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.mapper.RowMapperFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor;
package com.hubspot.rosetta.jdbi3; public class RosettaRowMapperFactory implements RowMapperFactory { @Override public Optional<RowMapper<?>> build(Type type, ConfigRegistry config) { if (accepts(type, config)) { return Optional.of((rs, ctx) -> { ObjectMapper objectMapper = ctx.getConfig(RosettaObjectMapper.class).getObjectMapper(); String tableName = SqlTableNameExtractor.extractTableName(ctx.getParsedSql().getSql());
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // } // Path: RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/RosettaRowMapperFactory.java import java.lang.reflect.Type; import java.util.Optional; import org.jdbi.v3.core.config.ConfigRegistry; import org.jdbi.v3.core.generic.GenericTypes; import org.jdbi.v3.core.mapper.ColumnMappers; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.mapper.RowMapperFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor; package com.hubspot.rosetta.jdbi3; public class RosettaRowMapperFactory implements RowMapperFactory { @Override public Optional<RowMapper<?>> build(Type type, ConfigRegistry config) { if (accepts(type, config)) { return Optional.of((rs, ctx) -> { ObjectMapper objectMapper = ctx.getConfig(RosettaObjectMapper.class).getObjectMapper(); String tableName = SqlTableNameExtractor.extractTableName(ctx.getParsedSql().getSql());
final RosettaMapper mapper = new RosettaMapper(type, objectMapper, tableName);
HubSpot/Rosetta
RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaObjectMapperOverride.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule;
package com.hubspot.rosetta.jdbi; public class RosettaObjectMapperOverride { public static final String ATTRIBUTE_NAME = "_rosetta_object_mapper"; private final ObjectMapper objectMapper; public RosettaObjectMapperOverride(ObjectMapper objectMapper) {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaObjectMapperOverride.java import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule; package com.hubspot.rosetta.jdbi; public class RosettaObjectMapperOverride { public static final String ATTRIBUTE_NAME = "_rosetta_object_mapper"; private final ObjectMapper objectMapper; public RosettaObjectMapperOverride(ObjectMapper objectMapper) {
this.objectMapper = objectMapper.copy().registerModule(new RosettaModule());
HubSpot/Rosetta
RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaObjectMapperOverride.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule;
package com.hubspot.rosetta.jdbi; public class RosettaObjectMapperOverride { public static final String ATTRIBUTE_NAME = "_rosetta_object_mapper"; private final ObjectMapper objectMapper; public RosettaObjectMapperOverride(ObjectMapper objectMapper) { this.objectMapper = objectMapper.copy().registerModule(new RosettaModule()); } public void override(DBI dbi) { override((IDBI) dbi); } public void override(IDBI dbi) { dbi.define(ATTRIBUTE_NAME, objectMapper); } public void override(Handle handle) { handle.define(ATTRIBUTE_NAME, objectMapper); } public void override(SQLStatement<?> statement) { statement.define(ATTRIBUTE_NAME, objectMapper); } public static ObjectMapper resolve(StatementContext context) { Object override = context.getAttribute(ATTRIBUTE_NAME);
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaObjectMapperOverride.java import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.internal.RosettaModule; package com.hubspot.rosetta.jdbi; public class RosettaObjectMapperOverride { public static final String ATTRIBUTE_NAME = "_rosetta_object_mapper"; private final ObjectMapper objectMapper; public RosettaObjectMapperOverride(ObjectMapper objectMapper) { this.objectMapper = objectMapper.copy().registerModule(new RosettaModule()); } public void override(DBI dbi) { override((IDBI) dbi); } public void override(IDBI dbi) { dbi.define(ATTRIBUTE_NAME, objectMapper); } public void override(Handle handle) { handle.define(ATTRIBUTE_NAME, objectMapper); } public void override(SQLStatement<?> statement) { statement.define(ATTRIBUTE_NAME, objectMapper); } public static ObjectMapper resolve(StatementContext context) { Object override = context.getAttribute(ATTRIBUTE_NAME);
return override == null ? Rosetta.getMapper() : (ObjectMapper) override;
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // }
import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException {
RosettaCreatorConstructorBean bean = Rosetta.getMapper().readValue(JSON, RosettaCreatorConstructorBean.class);
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // }
import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException {
RosettaCreatorConstructorBean bean = Rosetta.getMapper().readValue(JSON, RosettaCreatorConstructorBean.class);
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // }
import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException { RosettaCreatorConstructorBean bean = Rosetta.getMapper().readValue(JSON, RosettaCreatorConstructorBean.class); assertThat(bean.getStringProperty()).isEqualTo("value"); } @Test public void itWorksOnMethods() throws IOException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorConstructorBean.java // public class RosettaCreatorConstructorBean { // private final String stringProperty; // // @RosettaCreator // public RosettaCreatorConstructorBean(@JsonProperty("stringProperty") String stringProperty) { // this.stringProperty = stringProperty; // } // // public String getStringProperty() { // return stringProperty; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaCreatorMethodBean.java // public class RosettaCreatorMethodBean { // private final String stringProperty; // // private RosettaCreatorMethodBean(String stringProperty) { // this.stringProperty = stringProperty; // } // // @RosettaCreator // public static RosettaCreatorMethodBean fromString(@JsonProperty("stringProperty") String stringProperty) { // return new RosettaCreatorMethodBean(stringProperty); // } // // public String getStringProperty() { // return stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaCreatorTest.java import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaCreatorConstructorBean; import com.hubspot.rosetta.beans.RosettaCreatorMethodBean; import org.junit.Test; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaCreatorTest { private static final String JSON = "{\"stringProperty\":\"value\"}"; @Test public void itWorksOnConstructors() throws IOException { RosettaCreatorConstructorBean bean = Rosetta.getMapper().readValue(JSON, RosettaCreatorConstructorBean.class); assertThat(bean.getStringProperty()).isEqualTo("value"); } @Test public void itWorksOnMethods() throws IOException {
RosettaCreatorMethodBean bean = Rosetta.getMapper().readValue(JSON, RosettaCreatorMethodBean.class);
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/TestModule.java
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/ServiceLoaderBean.java // public class ServiceLoaderBean { // private int id; // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.hubspot.rosetta.beans.ServiceLoaderBean; import java.io.IOException;
package com.hubspot.rosetta; public class TestModule extends SimpleModule { public TestModule() {
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/ServiceLoaderBean.java // public class ServiceLoaderBean { // private int id; // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/TestModule.java import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.hubspot.rosetta.beans.ServiceLoaderBean; import java.io.IOException; package com.hubspot.rosetta; public class TestModule extends SimpleModule { public TestModule() {
addSerializer(new StdSerializer<ServiceLoaderBean>(ServiceLoaderBean.class) {
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaIgnoreTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.hubspot.rosetta.Rosetta;
package com.hubspot.rosetta.annotations; public class RosettaIgnoreTest { private static final String JSON = JsonNodeFactory.instance .objectNode() .put("stringProperty", "value") .toString(); private static final String JSON_WITH_IGNORED = JsonNodeFactory.instance .objectNode() .put("stringProperty", "value") .put("ignoredProperty", "ignored") .toString(); @Test public void itIgnoresMethodsWhenSerializing() throws JsonProcessingException { IgnoreMethodBean bean = new IgnoreMethodBean();
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaIgnoreTest.java import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.hubspot.rosetta.Rosetta; package com.hubspot.rosetta.annotations; public class RosettaIgnoreTest { private static final String JSON = JsonNodeFactory.instance .objectNode() .put("stringProperty", "value") .toString(); private static final String JSON_WITH_IGNORED = JsonNodeFactory.instance .objectNode() .put("stringProperty", "value") .put("ignoredProperty", "ignored") .toString(); @Test public void itIgnoresMethodsWhenSerializing() throws JsonProcessingException { IgnoreMethodBean bean = new IgnoreMethodBean();
assertThat(Rosetta.getMapper().writeValueAsString(bean))
HubSpot/Rosetta
RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/BindWithRosetta.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaBinder.java // public enum RosettaBinder { // INSTANCE; // // public interface Callback { // void bind(String key, Object value); // } // // public void bind(String prefix, JsonNode node, Callback callback) { // for (Iterator<Entry<String, JsonNode>> iterator = node.fields(); iterator.hasNext(); ) { // Entry<String, JsonNode> field = iterator.next(); // String key = prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(); // JsonNode value = field.getValue(); // // if (value.isObject()) { // bind(key, value, callback); // } else if (value.isArray()) { // List<Object> elements = new ArrayList<>(); // for (JsonNode element : value) { // elements.add(unwrapJsonValue(element)); // } // // callback.bind(key, elements); // } else { // callback.bind(key, unwrapJsonValue(value)); // } // } // } // // private Object unwrapJsonValue(JsonNode node) { // if (node.isNull()) { // return null; // } else if (node.isBoolean()) { // return node.booleanValue(); // } else if (node.isBinary()) { // return ((BinaryNode) node).binaryValue(); // } else if (node.isNumber()) { // return node.numberValue(); // } else { // return node.asText(); // } // } // }
import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizerFactory; import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizingAnnotation; import org.jdbi.v3.sqlobject.customizer.SqlStatementParameterCustomizer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaBinder; import com.hubspot.rosetta.jdbi3.BindWithRosetta.RosettaBinderFactory;
package com.hubspot.rosetta.jdbi3; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @SqlStatementCustomizingAnnotation(RosettaBinderFactory.class) public @interface BindWithRosetta { String prefix() default ""; class RosettaBinderFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementParameterCustomizer createForParameter( Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type paramType ) { return (stmt, arg) -> { ObjectMapper objectMapper = stmt.getConfig(RosettaObjectMapper.class).getObjectMapper(); JsonNode node = objectMapper.valueToTree(arg); String prefix = ((BindWithRosetta) annotation).prefix(); if (node.isValueNode() || node.isArray()) { node = objectMapper.createObjectNode().set(prefix.isEmpty() ? "it" : prefix, node); prefix = ""; } Map<String, Object> namedValues = new HashMap<>();
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaBinder.java // public enum RosettaBinder { // INSTANCE; // // public interface Callback { // void bind(String key, Object value); // } // // public void bind(String prefix, JsonNode node, Callback callback) { // for (Iterator<Entry<String, JsonNode>> iterator = node.fields(); iterator.hasNext(); ) { // Entry<String, JsonNode> field = iterator.next(); // String key = prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(); // JsonNode value = field.getValue(); // // if (value.isObject()) { // bind(key, value, callback); // } else if (value.isArray()) { // List<Object> elements = new ArrayList<>(); // for (JsonNode element : value) { // elements.add(unwrapJsonValue(element)); // } // // callback.bind(key, elements); // } else { // callback.bind(key, unwrapJsonValue(value)); // } // } // } // // private Object unwrapJsonValue(JsonNode node) { // if (node.isNull()) { // return null; // } else if (node.isBoolean()) { // return node.booleanValue(); // } else if (node.isBinary()) { // return ((BinaryNode) node).binaryValue(); // } else if (node.isNumber()) { // return node.numberValue(); // } else { // return node.asText(); // } // } // } // Path: RosettaJdbi3/src/main/java/com/hubspot/rosetta/jdbi3/BindWithRosetta.java import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizerFactory; import org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizingAnnotation; import org.jdbi.v3.sqlobject.customizer.SqlStatementParameterCustomizer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaBinder; import com.hubspot.rosetta.jdbi3.BindWithRosetta.RosettaBinderFactory; package com.hubspot.rosetta.jdbi3; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @SqlStatementCustomizingAnnotation(RosettaBinderFactory.class) public @interface BindWithRosetta { String prefix() default ""; class RosettaBinderFactory implements SqlStatementCustomizerFactory { @Override public SqlStatementParameterCustomizer createForParameter( Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type paramType ) { return (stmt, arg) -> { ObjectMapper objectMapper = stmt.getConfig(RosettaObjectMapper.class).getObjectMapper(); JsonNode node = objectMapper.valueToTree(arg); String prefix = ((BindWithRosetta) annotation).prefix(); if (node.isValueNode() || node.isArray()) { node = objectMapper.createObjectNode().set(prefix.isEmpty() ? "it" : prefix, node); prefix = ""; } Map<String, Object> namedValues = new HashMap<>();
RosettaBinder.INSTANCE.bind(prefix, node, namedValues::put);
HubSpot/Rosetta
RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/databind/AutoDiscoveredModule.java // public abstract class AutoDiscoveredModule extends Module { // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.databind.AutoDiscoveredModule; import com.hubspot.rosetta.internal.RosettaModule;
public static void setMapper(ObjectMapper mapper) { INSTANCE.set(mapper); } public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { mapper = mapper.copy(); // ObjectMapper#registerModules doesn't exist in 2.1.x for (Module module : MODULES) { mapper.registerModule(module); } return mapper; } private ObjectMapper get() { return MAPPER.get(); } private void set(ObjectMapper mapper) { MAPPER.set(cloneAndCustomize(mapper)); } private void add(Module module) { MODULES.add(module); MAPPER.get().registerModule(module); } private static List<Module> defaultModules() { List<Module> defaultModules = new ArrayList<Module>();
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/databind/AutoDiscoveredModule.java // public abstract class AutoDiscoveredModule extends Module { // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.databind.AutoDiscoveredModule; import com.hubspot.rosetta.internal.RosettaModule; public static void setMapper(ObjectMapper mapper) { INSTANCE.set(mapper); } public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { mapper = mapper.copy(); // ObjectMapper#registerModules doesn't exist in 2.1.x for (Module module : MODULES) { mapper.registerModule(module); } return mapper; } private ObjectMapper get() { return MAPPER.get(); } private void set(ObjectMapper mapper) { MAPPER.set(cloneAndCustomize(mapper)); } private void add(Module module) { MODULES.add(module); MAPPER.get().registerModule(module); } private static List<Module> defaultModules() { List<Module> defaultModules = new ArrayList<Module>();
defaultModules.add(new RosettaModule());
HubSpot/Rosetta
RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/databind/AutoDiscoveredModule.java // public abstract class AutoDiscoveredModule extends Module { // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // }
import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.databind.AutoDiscoveredModule; import com.hubspot.rosetta.internal.RosettaModule;
} public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { mapper = mapper.copy(); // ObjectMapper#registerModules doesn't exist in 2.1.x for (Module module : MODULES) { mapper.registerModule(module); } return mapper; } private ObjectMapper get() { return MAPPER.get(); } private void set(ObjectMapper mapper) { MAPPER.set(cloneAndCustomize(mapper)); } private void add(Module module) { MODULES.add(module); MAPPER.get().registerModule(module); } private static List<Module> defaultModules() { List<Module> defaultModules = new ArrayList<Module>(); defaultModules.add(new RosettaModule());
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/databind/AutoDiscoveredModule.java // public abstract class AutoDiscoveredModule extends Module { // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/internal/RosettaModule.java // @SuppressWarnings("serial") // public class RosettaModule extends Module { // // @Override // public String getModuleName() { // return "RosettaModule"; // } // // @Override // public Version version() { // return Version.unknownVersion(); // } // // @Override // public void setupModule(SetupContext context) { // context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier()); // // ObjectCodec codec = context.getOwner(); // if (codec instanceof ObjectMapper) { // ObjectMapper mapper = (ObjectMapper) codec; // // context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper)); // // mapper.setSerializerProvider(new DefaultSerializerProvider.Impl()); // mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); // mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // mapper.setSerializationInclusion(Include.ALWAYS); // } // } // } // Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.databind.AutoDiscoveredModule; import com.hubspot.rosetta.internal.RosettaModule; } public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { mapper = mapper.copy(); // ObjectMapper#registerModules doesn't exist in 2.1.x for (Module module : MODULES) { mapper.registerModule(module); } return mapper; } private ObjectMapper get() { return MAPPER.get(); } private void set(ObjectMapper mapper) { MAPPER.set(cloneAndCustomize(mapper)); } private void add(Module module) { MODULES.add(module); MAPPER.get().registerModule(module); } private static List<Module> defaultModules() { List<Module> defaultModules = new ArrayList<Module>(); defaultModules.add(new RosettaModule());
for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) {
HubSpot/Rosetta
RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaMapperFactory.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // }
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.BuiltInArgumentFactory; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor;
package com.hubspot.rosetta.jdbi; public class RosettaMapperFactory implements ResultSetMapperFactory { @Override public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) { return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type)); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public ResultSetMapper mapperFor(Class rawType, StatementContext ctx) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(ctx); final Type genericType; if (ctx.getSqlObjectMethod() == null) { genericType = rawType; } else { genericType = determineGenericReturnType(rawType, ctx.getSqlObjectMethod().getGenericReturnType()); }
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // } // Path: RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaMapperFactory.java import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.BuiltInArgumentFactory; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor; package com.hubspot.rosetta.jdbi; public class RosettaMapperFactory implements ResultSetMapperFactory { @Override public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) { return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type)); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public ResultSetMapper mapperFor(Class rawType, StatementContext ctx) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(ctx); final Type genericType; if (ctx.getSqlObjectMethod() == null) { genericType = rawType; } else { genericType = determineGenericReturnType(rawType, ctx.getSqlObjectMethod().getGenericReturnType()); }
String tableName = SqlTableNameExtractor.extractTableName(ctx.getRewrittenSql());
HubSpot/Rosetta
RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaMapperFactory.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // }
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.BuiltInArgumentFactory; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor;
package com.hubspot.rosetta.jdbi; public class RosettaMapperFactory implements ResultSetMapperFactory { @Override public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) { return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type)); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public ResultSetMapper mapperFor(Class rawType, StatementContext ctx) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(ctx); final Type genericType; if (ctx.getSqlObjectMethod() == null) { genericType = rawType; } else { genericType = determineGenericReturnType(rawType, ctx.getSqlObjectMethod().getGenericReturnType()); } String tableName = SqlTableNameExtractor.extractTableName(ctx.getRewrittenSql());
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java // public class RosettaMapper<T> { // private static TableNameExtractor TABLE_NAME_EXTRACTOR = chooseTableNameExtractor(); // // private final JavaType type; // private final ObjectMapper objectMapper; // private final String tableName; // // public RosettaMapper(Class<T> type) { // this(type, Rosetta.getMapper()); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper) { // this(type, objectMapper, null); // } // // public RosettaMapper(Class<T> type, String tableName) { // this(type, Rosetta.getMapper(), tableName); // } // // public RosettaMapper(Class<T> type, ObjectMapper objectMapper, String tableName) { // this((Type) type, objectMapper, tableName); // } // // public RosettaMapper(Type type, ObjectMapper objectMapper, String tableName) { // this.type = objectMapper.constructType(type); // this.objectMapper = objectMapper; // this.tableName = tableName; // } // // /** // * Map a single ResultSet row to a T instance. // * // * @throws SQLException // */ // public T mapRow(ResultSet rs) throws SQLException { // Map<String, Object> map = new HashMap<String, Object>(); // ResultSetMetaData metadata = rs.getMetaData(); // // for (int i = 1; i <= metadata.getColumnCount(); ++i) { // String label = metadata.getColumnLabel(i); // // final Object value; // // calling getObject on a BLOB/CLOB produces weird results // switch (metadata.getColumnType(i)) { // case Types.BLOB: // value = rs.getBytes(i); // break; // case Types.CLOB: // value = rs.getString(i); // break; // default: // value = rs.getObject(i); // } // // // don't use table name extractor because we don't want aliased table name // boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i)); // String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i); // if (tableName != null && !tableName.isEmpty()) { // String qualifiedName = tableName + "." + metadata.getColumnName(i); // add(map, qualifiedName, value, overwrite); // } // // add(map, label, value, overwrite); // } // // return objectMapper.convertValue(map, type); // } // // private void add(Map<String, Object> map, String label, Object value, boolean overwrite) { // if (label.contains(".")) { // int periodIndex = label.indexOf('.'); // String prefix = label.substring(0, periodIndex); // String suffix = label.substring(periodIndex + 1); // // @SuppressWarnings("unchecked") // Map<String, Object> submap = (Map<String, Object>) map.get(prefix); // if (submap == null) { // submap = new HashMap<>(); // map.put(prefix, submap); // } // // add(submap, suffix, value, overwrite); // } else { // if (overwrite || !map.containsKey(label)) { // map.put(label, value); // } // } // } // // private static TableNameExtractor chooseTableNameExtractor() { // try { // Class.forName("com.mysql.jdbc.ResultSetMetaData"); // return (TableNameExtractor) Class.forName("com.mysql.jdbc.MysqlTableNameExtractor").newInstance(); // } catch (Exception e) { // return new TableNameExtractor.Default(); // } // } // } // // Path: RosettaCore/src/main/java/com/hubspot/rosetta/util/SqlTableNameExtractor.java // public class SqlTableNameExtractor { // // private SqlTableNameExtractor() { // throw new AssertionError(); // } // // public static String extractTableName(final String sql) { // String lowerCaseSql = sql.toLowerCase(); // // String from = " from "; // int fromIndex = lowerCaseSql.indexOf(from); // if (fromIndex < 0) { // return null; // } // // String tableString = sql.substring(fromIndex + from.length()); // if (tableString.startsWith("(")) { // return null; // } // // int endTableIndex = -1; // for (int i = 0; i < tableString.length(); i++) { // char c = tableString.charAt(i); // if (c == ' ' || c == ',' || c == ';') { // endTableIndex = i; // break; // } // } // // return endTableIndex < 0 ? tableString : tableString.substring(0, endTableIndex); // } // } // Path: RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaMapperFactory.java import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.BuiltInArgumentFactory; import org.skife.jdbi.v2.ResultSetMapperFactory; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaMapper; import com.hubspot.rosetta.util.SqlTableNameExtractor; package com.hubspot.rosetta.jdbi; public class RosettaMapperFactory implements ResultSetMapperFactory { @Override public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) { return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type)); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public ResultSetMapper mapperFor(Class rawType, StatementContext ctx) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(ctx); final Type genericType; if (ctx.getSqlObjectMethod() == null) { genericType = rawType; } else { genericType = determineGenericReturnType(rawType, ctx.getSqlObjectMethod().getGenericReturnType()); } String tableName = SqlTableNameExtractor.extractTableName(ctx.getRewrittenSql());
final RosettaMapper mapper = new RosettaMapper(genericType, objectMapper, tableName);
HubSpot/Rosetta
RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaJdbiBinder.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaBinder.java // public enum RosettaBinder { // INSTANCE; // // public interface Callback { // void bind(String key, Object value); // } // // public void bind(String prefix, JsonNode node, Callback callback) { // for (Iterator<Entry<String, JsonNode>> iterator = node.fields(); iterator.hasNext(); ) { // Entry<String, JsonNode> field = iterator.next(); // String key = prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(); // JsonNode value = field.getValue(); // // if (value.isObject()) { // bind(key, value, callback); // } else if (value.isArray()) { // List<Object> elements = new ArrayList<>(); // for (JsonNode element : value) { // elements.add(unwrapJsonValue(element)); // } // // callback.bind(key, elements); // } else { // callback.bind(key, unwrapJsonValue(value)); // } // } // } // // private Object unwrapJsonValue(JsonNode node) { // if (node.isNull()) { // return null; // } else if (node.isBoolean()) { // return node.booleanValue(); // } else if (node.isBinary()) { // return ((BinaryNode) node).binaryValue(); // } else if (node.isNumber()) { // return node.numberValue(); // } else { // return node.asText(); // } // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaBinder; import com.hubspot.rosetta.RosettaBinder.Callback; import org.skife.jdbi.v2.SQLStatement; import com.fasterxml.jackson.databind.JsonNode; import org.skife.jdbi.v2.sqlobject.Binder;
package com.hubspot.rosetta.jdbi; public enum RosettaJdbiBinder implements Binder<BindWithRosetta, Object> { INSTANCE; @Override public void bind(final SQLStatement<?> q, BindWithRosetta bind, Object arg) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(q.getContext()); JsonNode node = objectMapper.valueToTree(arg); String prefix = bind.value(); if (node.isValueNode() || node.isArray()) { node = objectMapper.createObjectNode().set(prefix.isEmpty() ? "it" : prefix, node); prefix = ""; }
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/RosettaBinder.java // public enum RosettaBinder { // INSTANCE; // // public interface Callback { // void bind(String key, Object value); // } // // public void bind(String prefix, JsonNode node, Callback callback) { // for (Iterator<Entry<String, JsonNode>> iterator = node.fields(); iterator.hasNext(); ) { // Entry<String, JsonNode> field = iterator.next(); // String key = prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(); // JsonNode value = field.getValue(); // // if (value.isObject()) { // bind(key, value, callback); // } else if (value.isArray()) { // List<Object> elements = new ArrayList<>(); // for (JsonNode element : value) { // elements.add(unwrapJsonValue(element)); // } // // callback.bind(key, elements); // } else { // callback.bind(key, unwrapJsonValue(value)); // } // } // } // // private Object unwrapJsonValue(JsonNode node) { // if (node.isNull()) { // return null; // } else if (node.isBoolean()) { // return node.booleanValue(); // } else if (node.isBinary()) { // return ((BinaryNode) node).binaryValue(); // } else if (node.isNumber()) { // return node.numberValue(); // } else { // return node.asText(); // } // } // } // Path: RosettaJdbi/src/main/java/com/hubspot/rosetta/jdbi/RosettaJdbiBinder.java import com.fasterxml.jackson.databind.ObjectMapper; import com.hubspot.rosetta.RosettaBinder; import com.hubspot.rosetta.RosettaBinder.Callback; import org.skife.jdbi.v2.SQLStatement; import com.fasterxml.jackson.databind.JsonNode; import org.skife.jdbi.v2.sqlobject.Binder; package com.hubspot.rosetta.jdbi; public enum RosettaJdbiBinder implements Binder<BindWithRosetta, Object> { INSTANCE; @Override public void bind(final SQLStatement<?> q, BindWithRosetta bind, Object arg) { ObjectMapper objectMapper = RosettaObjectMapperOverride.resolve(q.getContext()); JsonNode node = objectMapper.valueToTree(arg); String prefix = bind.value(); if (node.isValueNode() || node.isArray()) { node = objectMapper.createObjectNode().set(prefix.isEmpty() ? "it" : prefix, node); prefix = ""; }
RosettaBinder.INSTANCE.bind(prefix, node, new Callback() {
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaValueTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaValueBean.java // public class RosettaValueBean { // private String stringProperty; // // @RosettaValue // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaValueBean; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaValueTest { @Test public void itCallsRosettaValueMethod() throws JsonProcessingException {
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaValueBean.java // public class RosettaValueBean { // private String stringProperty; // // @RosettaValue // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaValueTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaValueBean; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaValueTest { @Test public void itCallsRosettaValueMethod() throws JsonProcessingException {
RosettaValueBean bean = new RosettaValueBean();
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaValueTest.java
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaValueBean.java // public class RosettaValueBean { // private String stringProperty; // // @RosettaValue // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaValueBean; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
package com.hubspot.rosetta.annotations; public class RosettaValueTest { @Test public void itCallsRosettaValueMethod() throws JsonProcessingException { RosettaValueBean bean = new RosettaValueBean(); bean.setStringProperty("value");
// Path: RosettaCore/src/main/java/com/hubspot/rosetta/Rosetta.java // public enum Rosetta { // INSTANCE; // // private static final List<Module> MODULES = new CopyOnWriteArrayList<Module>(defaultModules()); // private static final AtomicReference<ObjectMapper> MAPPER = new AtomicReference<ObjectMapper>(cloneAndCustomize(new ObjectMapper())); // // public static ObjectMapper getMapper() { // return INSTANCE.get(); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void addModule(Module module) { // INSTANCE.add(module); // } // // /** // * @deprecated To customize the ObjectMapper, use {@link com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride}. // */ // @Deprecated // public static void setMapper(ObjectMapper mapper) { // INSTANCE.set(mapper); // } // // public static ObjectMapper cloneAndCustomize(ObjectMapper mapper) { // mapper = mapper.copy(); // // // ObjectMapper#registerModules doesn't exist in 2.1.x // for (Module module : MODULES) { // mapper.registerModule(module); // } // // return mapper; // } // // private ObjectMapper get() { // return MAPPER.get(); // } // // private void set(ObjectMapper mapper) { // MAPPER.set(cloneAndCustomize(mapper)); // } // // private void add(Module module) { // MODULES.add(module); // MAPPER.get().registerModule(module); // } // // private static List<Module> defaultModules() { // List<Module> defaultModules = new ArrayList<Module>(); // defaultModules.add(new RosettaModule()); // // for (Module module : ServiceLoader.load(AutoDiscoveredModule.class)) { // defaultModules.add(module); // } // // for (Module module : ServiceLoader.load(Module.class)) { // defaultModules.add(module); // } // // return defaultModules; // } // } // // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/RosettaValueBean.java // public class RosettaValueBean { // private String stringProperty; // // @RosettaValue // public String getStringProperty() { // return stringProperty; // } // // public void setStringProperty(String stringProperty) { // this.stringProperty = stringProperty; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/annotations/RosettaValueTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.hubspot.rosetta.Rosetta; import com.hubspot.rosetta.beans.RosettaValueBean; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; package com.hubspot.rosetta.annotations; public class RosettaValueTest { @Test public void itCallsRosettaValueMethod() throws JsonProcessingException { RosettaValueBean bean = new RosettaValueBean(); bean.setStringProperty("value");
assertThat(Rosetta.getMapper().writeValueAsString(bean)).isEqualTo("\"value\"");
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonTypeInfoBean.java
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonTypeInfoBean.java // class ConcreteStoredAsJsonTypeInfo implements StoredAsJsonTypeInfoBean { // private String generalValue; // private String concreteValue; // // @Override // public String getType() { // return "concrete"; // } // // @Override // public String getGeneralValue() { // return generalValue; // } // // public void setGeneralValue(String generalValue) { // this.generalValue = generalValue; // } // // public String getConcreteValue() { // return concreteValue; // } // // public void setConcreteValue(String concreteValue) { // this.concreteValue = concreteValue; // } // }
import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.hubspot.rosetta.beans.StoredAsJsonTypeInfoBean.ConcreteStoredAsJsonTypeInfo;
package com.hubspot.rosetta.beans; @JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, property = "type") @JsonSubTypes({
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonTypeInfoBean.java // class ConcreteStoredAsJsonTypeInfo implements StoredAsJsonTypeInfoBean { // private String generalValue; // private String concreteValue; // // @Override // public String getType() { // return "concrete"; // } // // @Override // public String getGeneralValue() { // return generalValue; // } // // public void setGeneralValue(String generalValue) { // this.generalValue = generalValue; // } // // public String getConcreteValue() { // return concreteValue; // } // // public void setConcreteValue(String concreteValue) { // this.concreteValue = concreteValue; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonTypeInfoBean.java import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.hubspot.rosetta.beans.StoredAsJsonTypeInfoBean.ConcreteStoredAsJsonTypeInfo; package com.hubspot.rosetta.beans; @JsonTypeInfo(use = Id.NAME, include = As.EXISTING_PROPERTY, property = "type") @JsonSubTypes({
@JsonSubTypes.Type(value = ConcreteStoredAsJsonTypeInfo.class, name = "concrete")
HubSpot/Rosetta
RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonListTypeInfoBean.java
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonListTypeInfoBean.java // public static class ConcreteStoredAsJsonList extends StoredAsJsonListTypeInfoBean { // private List<InnerBean> innerBeans; // // @Override // public List<InnerBean> getInnerBeans() { // return innerBeans; // } // // public void setInnerBeans(List<InnerBean> innerBeans) { // this.innerBeans = innerBeans; // } // }
import java.util.List; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.hubspot.rosetta.annotations.StoredAsJson; import com.hubspot.rosetta.beans.StoredAsJsonListTypeInfoBean.ConcreteStoredAsJsonList;
package com.hubspot.rosetta.beans; @JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY) @JsonSubTypes({
// Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonListTypeInfoBean.java // public static class ConcreteStoredAsJsonList extends StoredAsJsonListTypeInfoBean { // private List<InnerBean> innerBeans; // // @Override // public List<InnerBean> getInnerBeans() { // return innerBeans; // } // // public void setInnerBeans(List<InnerBean> innerBeans) { // this.innerBeans = innerBeans; // } // } // Path: RosettaCore/src/test/java/com/hubspot/rosetta/beans/StoredAsJsonListTypeInfoBean.java import java.util.List; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.hubspot.rosetta.annotations.StoredAsJson; import com.hubspot.rosetta.beans.StoredAsJsonListTypeInfoBean.ConcreteStoredAsJsonList; package com.hubspot.rosetta.beans; @JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY) @JsonSubTypes({
@JsonSubTypes.Type(value = ConcreteStoredAsJsonList.class)
pcdv/jflask
jflask/src/test/java/net/jflask/test/LoginTest5.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.Route; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * Try to reproduce bug where failed login does not prevent user from * accessing restricted pages. Turns out the browser (chrome) had several * duplicates of the session cookie and deleting one on logout was not enough * to disable the session (should be fixed now that cookie is set with a path). * * @author pcdv */ public class LoginTest5 extends AbstractAppTest { @LoginNotRequired @Route(value = "/auth/login", method = "POST")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/LoginTest5.java import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.Route; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * Try to reproduce bug where failed login does not prevent user from * accessing restricted pages. Turns out the browser (chrome) had several * duplicates of the session cookie and deleting one on logout was not enough * to disable the session (should be fixed now that cookie is set with a path). * * @author pcdv */ public class LoginTest5 extends AbstractAppTest { @LoginNotRequired @Route(value = "/auth/login", method = "POST")
public CustomResponse login() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception {
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // } // Path: jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception {
app.addErrorHandler(new ErrorHandler() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // } // Path: jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override
public void onError(int status, Request request, Throwable t) {
pcdv/jflask
jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { // this is a hack (future version should allow to do it in a clean way)
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // } // Path: jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { // this is a hack (future version should allow to do it in a clean way)
HttpExchange ex = ((SunRequest) request).getExchange();
pcdv/jflask
jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { // this is a hack (future version should allow to do it in a clean way) HttpExchange ex = ((SunRequest) request).getExchange(); try { ex.sendResponseHeaders(555, 0); ex.getResponseBody().write("hello".getBytes()); ex.close(); } catch (IOException ignored) { } } }); try { client.get("/"); }
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/test/java/net/jflask/test/util/HttpException.java // public class HttpException extends RuntimeException { // private final int responseCode; // // public HttpException(int responseCode, String message) { // super(message); // this.responseCode = responseCode; // } // // public int getResponseCode() { // return responseCode; // } // } // Path: jflask/src/test/java/net/jflask/test/ErrorHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.test.util.HttpException; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * @author pcdv */ public class ErrorHandlerTest extends AbstractAppTest { @Route("/") public String foo() { throw new IllegalStateException("fail"); } /** * Check that a error handler can customize the response sent to the client. */ @Test public void testHandlerSendsContent() throws Exception { app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { // this is a hack (future version should allow to do it in a clean way) HttpExchange ex = ((SunRequest) request).getExchange(); try { ex.sendResponseHeaders(555, 0); ex.getResponseBody().write("hello".getBytes()); ex.close(); } catch (IOException ignored) { } } }); try { client.get("/"); }
catch (HttpException e) {
pcdv/jflask
jflask/src/test/java/net/jflask/test/RedirectTest.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.Route; import net.jflask.CustomResponse; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Misc Redirect tests. */ public class RedirectTest extends AbstractAppTest { @Route("/foo")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/RedirectTest.java import net.jflask.Route; import net.jflask.CustomResponse; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Misc Redirect tests. */ public class RedirectTest extends AbstractAppTest { @Route("/foo")
public CustomResponse foo() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception {
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // } // Path: jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test; package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception {
app.setUnknownPageHandler(new UnknownPageHandler() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception { app.setUnknownPageHandler(new UnknownPageHandler() { @Override
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // } // Path: jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test; package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception { app.setUnknownPageHandler(new UnknownPageHandler() { @Override
public void handle(Request r) throws IOException {
pcdv/jflask
jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // }
import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception { app.setUnknownPageHandler(new UnknownPageHandler() { @Override public void handle(Request r) throws IOException {
// Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SunRequest.java // public class SunRequest implements Request, Response { // // private final HttpExchange exchange; // // private final int qsMark; // // private final String uri; // // private String form; // // public SunRequest(HttpExchange r) { // this.exchange = r; // this.uri = r.getRequestURI().toString(); // this.qsMark = uri.indexOf('?'); // } // // public String getRequestURI() { // return qsMark >= 0 ? uri.substring(0, qsMark) : uri; // } // // public String getQueryString() { // return qsMark >= 0 ? uri.substring(qsMark + 1) : null; // } // // public HttpExchange getExchange() { // return exchange; // } // // public String getMethod() { // return exchange.getRequestMethod(); // } // // public String getArg(String name, String def) { // if (qsMark == -1) // return def; // return parseArg(name, def, getQueryString()); // } // // private String parseArg(String name, String def, String encoded) { // String[] tok = encoded.split("&"); // for (String s : tok) { // if (s.startsWith(name)) { // if (s.length() > name.length() && s.charAt(name.length()) == '=') // return s.substring(name.length() + 1); // } // } // return def; // } // // @Override // public String getForm(String field) { // try { // if (form == null) // form = new String(IO.readFully(getInputStream())); // return parseArg(field, null, form); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public List<String> getArgs(String name) { // // TODO // return null; // } // // public InputStream getInputStream() { // return exchange.getRequestBody(); // } // // // /////////// Response methods // // public void addHeader(String header, String value) { // exchange.getResponseHeaders().add(header, value); // } // // public void setStatus(int status) { // try { // exchange.sendResponseHeaders(status, 0); // } // catch (IOException e) { // throw new RuntimeException(e); // } // } // // public OutputStream getOutputStream() { // return exchange.getResponseBody(); // } // // } // // Path: jflask/src/main/java/net/jflask/UnknownPageHandler.java // public interface UnknownPageHandler { // // void handle(Request r) throws IOException; // } // Path: jflask/src/test/java/net/jflask/test/UnknownPageHandlerTest.java import java.io.IOException; import com.sun.net.httpserver.HttpExchange; import net.jflask.Request; import net.jflask.Route; import net.jflask.SunRequest; import net.jflask.UnknownPageHandler; import org.junit.Assert; import org.junit.Test; package net.jflask.test; public class UnknownPageHandlerTest extends AbstractAppTest { @Route("/foo") public String foo() { return "bar"; } @Route("/") public String foo2() { return "root"; } @Test public void testIt() throws Exception { app.setUnknownPageHandler(new UnknownPageHandler() { @Override public void handle(Request r) throws IOException {
HttpExchange e = ((SunRequest) r).getExchange();
pcdv/jflask
jflask/src/test/java/net/jflask/test/LoginTest2.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.LoginPage; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Variant of LoginTest that uses @LoginNotRequired and * {@link net.jflask.App#setRequireLoggedInByDefault(boolean)}. * * @author pcdv */ public class LoginTest2 extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/LoginTest2.java import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.LoginPage; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Variant of LoginTest that uses @LoginNotRequired and * {@link net.jflask.App#setRequireLoggedInByDefault(boolean)}. * * @author pcdv */ public class LoginTest2 extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
public CustomResponse logout() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/HttpErrorTest.java
// Path: jflask/src/main/java/net/jflask/HttpError.java // public class HttpError extends RuntimeException { // private final int status; // // public HttpError(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // }
import net.jflask.HttpError; import net.jflask.Route; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * @author pcdv */ public class HttpErrorTest extends AbstractAppTest { @Route("/200") public String gen200() {
// Path: jflask/src/main/java/net/jflask/HttpError.java // public class HttpError extends RuntimeException { // private final int status; // // public HttpError(int status, String message) { // super(message); // this.status = status; // } // // public int getStatus() { // return status; // } // } // Path: jflask/src/test/java/net/jflask/test/HttpErrorTest.java import net.jflask.HttpError; import net.jflask.Route; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * @author pcdv */ public class HttpErrorTest extends AbstractAppTest { @Route("/200") public String gen200() {
throw new HttpError(200, "Works");
pcdv/jflask
jflask/src/test/java/net/jflask/test/LoginTest4.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.Route; import org.junit.Assert; import org.junit.Test;
package net.jflask.test; /** * This test used to fail because Set-Cookie header did not include any path. * * @author pcdv */ public class LoginTest4 extends AbstractAppTest { @LoginNotRequired @Route(value = "/auth/login", method = "POST")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/LoginTest4.java import net.jflask.CustomResponse; import net.jflask.LoginNotRequired; import net.jflask.Route; import org.junit.Assert; import org.junit.Test; package net.jflask.test; /** * This test used to fail because Set-Cookie header did not include any path. * * @author pcdv */ public class LoginTest4 extends AbstractAppTest { @LoginNotRequired @Route(value = "/auth/login", method = "POST")
public CustomResponse login() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/util/SimpleClient.java
// Path: jflask/src/main/java/net/jflask/sun/WebServer.java // public class WebServer { // // private HttpServer srv; // // private final ExecutorService pool; // // private InetSocketAddress address; // // private final Map<String, RequestHandler> handlers = new Hashtable<>(); // // public WebServer(int port, ExecutorService pool) { // if (pool == null) // pool = Executors.newCachedThreadPool(); // this.pool = pool; // this.address = new InetSocketAddress(port); // } // // public WebServer addHandler(String path, RequestHandler handler) { // RequestHandler old = handlers.get(path); // if (old != null) { // if (old.getApp() != handler.getApp()) // throw new RuntimeException(String.format( // "Path %s already used by app %s", // path, // old.getApp())); // else // throw new RuntimeException("Path already used: " + path); // } // // handlers.put(path, handler); // if (srv != null) // srv.createContext(path, handler.asHttpHandler()); // return this; // } // // public void setPort(int port) { // this.address = new InetSocketAddress(port); // } // // private void checkNotStarted() { // if (srv != null) // throw new IllegalStateException("Already started"); // } // // /** // * Shuts down the web sever. // * <p/> // * WARNING: with JDK6, HttpServer creates a zombie thread (blocked on a // * sleep()). No problem with JDK 1.7.0_40. // */ // public void close() { // this.srv.stop(0); // pool.shutdownNow(); // } // // public int getPort() { // return srv.getAddress().getPort(); // } // // public void start() throws IOException { // this.srv = HttpServer.create(address, 0); // this.srv.setExecutor(pool); // for (Map.Entry<String, RequestHandler> e : handlers.entrySet()) { // String path = e.getKey(); // if (path.isEmpty()) // path = "/"; // srv.createContext(path, e.getValue().asHttpHandler()); // } // // this.srv.start(); // } // // public boolean isStarted() { // return srv != null; // } // } // // Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.xml.ws.http.HTTPException; import net.jflask.sun.WebServer; import net.jflask.util.IO;
package net.jflask.test.util; /** * Minimal HTTP client that mimics the behaviour of a browser, eg. by allowing * cookies. * * @author pcdv */ public class SimpleClient { private final String rootUrl; private CookieManager cookies; public SimpleClient(String host, int port) { this("http://" + host + ":" + port); } public SimpleClient(String rootUrl) { this.rootUrl = rootUrl; this.cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL); // WTF: there is no non-static way to bind a CookieHandler to an // URLConnection! CookieHandler.setDefault(cookies); }
// Path: jflask/src/main/java/net/jflask/sun/WebServer.java // public class WebServer { // // private HttpServer srv; // // private final ExecutorService pool; // // private InetSocketAddress address; // // private final Map<String, RequestHandler> handlers = new Hashtable<>(); // // public WebServer(int port, ExecutorService pool) { // if (pool == null) // pool = Executors.newCachedThreadPool(); // this.pool = pool; // this.address = new InetSocketAddress(port); // } // // public WebServer addHandler(String path, RequestHandler handler) { // RequestHandler old = handlers.get(path); // if (old != null) { // if (old.getApp() != handler.getApp()) // throw new RuntimeException(String.format( // "Path %s already used by app %s", // path, // old.getApp())); // else // throw new RuntimeException("Path already used: " + path); // } // // handlers.put(path, handler); // if (srv != null) // srv.createContext(path, handler.asHttpHandler()); // return this; // } // // public void setPort(int port) { // this.address = new InetSocketAddress(port); // } // // private void checkNotStarted() { // if (srv != null) // throw new IllegalStateException("Already started"); // } // // /** // * Shuts down the web sever. // * <p/> // * WARNING: with JDK6, HttpServer creates a zombie thread (blocked on a // * sleep()). No problem with JDK 1.7.0_40. // */ // public void close() { // this.srv.stop(0); // pool.shutdownNow(); // } // // public int getPort() { // return srv.getAddress().getPort(); // } // // public void start() throws IOException { // this.srv = HttpServer.create(address, 0); // this.srv.setExecutor(pool); // for (Map.Entry<String, RequestHandler> e : handlers.entrySet()) { // String path = e.getKey(); // if (path.isEmpty()) // path = "/"; // srv.createContext(path, e.getValue().asHttpHandler()); // } // // this.srv.start(); // } // // public boolean isStarted() { // return srv != null; // } // } // // Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // Path: jflask/src/test/java/net/jflask/test/util/SimpleClient.java import java.io.IOException; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.xml.ws.http.HTTPException; import net.jflask.sun.WebServer; import net.jflask.util.IO; package net.jflask.test.util; /** * Minimal HTTP client that mimics the behaviour of a browser, eg. by allowing * cookies. * * @author pcdv */ public class SimpleClient { private final String rootUrl; private CookieManager cookies; public SimpleClient(String host, int port) { this("http://" + host + ":" + port); } public SimpleClient(String rootUrl) { this.rootUrl = rootUrl; this.cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL); // WTF: there is no non-static way to bind a CookieHandler to an // URLConnection! CookieHandler.setDefault(cookies); }
public SimpleClient(WebServer ws) {
pcdv/jflask
jflask/src/test/java/net/jflask/test/util/SimpleClient.java
// Path: jflask/src/main/java/net/jflask/sun/WebServer.java // public class WebServer { // // private HttpServer srv; // // private final ExecutorService pool; // // private InetSocketAddress address; // // private final Map<String, RequestHandler> handlers = new Hashtable<>(); // // public WebServer(int port, ExecutorService pool) { // if (pool == null) // pool = Executors.newCachedThreadPool(); // this.pool = pool; // this.address = new InetSocketAddress(port); // } // // public WebServer addHandler(String path, RequestHandler handler) { // RequestHandler old = handlers.get(path); // if (old != null) { // if (old.getApp() != handler.getApp()) // throw new RuntimeException(String.format( // "Path %s already used by app %s", // path, // old.getApp())); // else // throw new RuntimeException("Path already used: " + path); // } // // handlers.put(path, handler); // if (srv != null) // srv.createContext(path, handler.asHttpHandler()); // return this; // } // // public void setPort(int port) { // this.address = new InetSocketAddress(port); // } // // private void checkNotStarted() { // if (srv != null) // throw new IllegalStateException("Already started"); // } // // /** // * Shuts down the web sever. // * <p/> // * WARNING: with JDK6, HttpServer creates a zombie thread (blocked on a // * sleep()). No problem with JDK 1.7.0_40. // */ // public void close() { // this.srv.stop(0); // pool.shutdownNow(); // } // // public int getPort() { // return srv.getAddress().getPort(); // } // // public void start() throws IOException { // this.srv = HttpServer.create(address, 0); // this.srv.setExecutor(pool); // for (Map.Entry<String, RequestHandler> e : handlers.entrySet()) { // String path = e.getKey(); // if (path.isEmpty()) // path = "/"; // srv.createContext(path, e.getValue().asHttpHandler()); // } // // this.srv.start(); // } // // public boolean isStarted() { // return srv != null; // } // } // // Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.xml.ws.http.HTTPException; import net.jflask.sun.WebServer; import net.jflask.util.IO;
package net.jflask.test.util; /** * Minimal HTTP client that mimics the behaviour of a browser, eg. by allowing * cookies. * * @author pcdv */ public class SimpleClient { private final String rootUrl; private CookieManager cookies; public SimpleClient(String host, int port) { this("http://" + host + ":" + port); } public SimpleClient(String rootUrl) { this.rootUrl = rootUrl; this.cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL); // WTF: there is no non-static way to bind a CookieHandler to an // URLConnection! CookieHandler.setDefault(cookies); } public SimpleClient(WebServer ws) { this("http://localhost:"+ws.getPort()); } /** * GETs data from the server at specified path. */ public String get(String path) throws IOException { URL url = new URL(rootUrl + path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(false); // https://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error con.getResponseCode(); InputStream err = con.getErrorStream(); if (err != null) {
// Path: jflask/src/main/java/net/jflask/sun/WebServer.java // public class WebServer { // // private HttpServer srv; // // private final ExecutorService pool; // // private InetSocketAddress address; // // private final Map<String, RequestHandler> handlers = new Hashtable<>(); // // public WebServer(int port, ExecutorService pool) { // if (pool == null) // pool = Executors.newCachedThreadPool(); // this.pool = pool; // this.address = new InetSocketAddress(port); // } // // public WebServer addHandler(String path, RequestHandler handler) { // RequestHandler old = handlers.get(path); // if (old != null) { // if (old.getApp() != handler.getApp()) // throw new RuntimeException(String.format( // "Path %s already used by app %s", // path, // old.getApp())); // else // throw new RuntimeException("Path already used: " + path); // } // // handlers.put(path, handler); // if (srv != null) // srv.createContext(path, handler.asHttpHandler()); // return this; // } // // public void setPort(int port) { // this.address = new InetSocketAddress(port); // } // // private void checkNotStarted() { // if (srv != null) // throw new IllegalStateException("Already started"); // } // // /** // * Shuts down the web sever. // * <p/> // * WARNING: with JDK6, HttpServer creates a zombie thread (blocked on a // * sleep()). No problem with JDK 1.7.0_40. // */ // public void close() { // this.srv.stop(0); // pool.shutdownNow(); // } // // public int getPort() { // return srv.getAddress().getPort(); // } // // public void start() throws IOException { // this.srv = HttpServer.create(address, 0); // this.srv.setExecutor(pool); // for (Map.Entry<String, RequestHandler> e : handlers.entrySet()) { // String path = e.getKey(); // if (path.isEmpty()) // path = "/"; // srv.createContext(path, e.getValue().asHttpHandler()); // } // // this.srv.start(); // } // // public boolean isStarted() { // return srv != null; // } // } // // Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // Path: jflask/src/test/java/net/jflask/test/util/SimpleClient.java import java.io.IOException; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import javax.xml.ws.http.HTTPException; import net.jflask.sun.WebServer; import net.jflask.util.IO; package net.jflask.test.util; /** * Minimal HTTP client that mimics the behaviour of a browser, eg. by allowing * cookies. * * @author pcdv */ public class SimpleClient { private final String rootUrl; private CookieManager cookies; public SimpleClient(String host, int port) { this("http://" + host + ":" + port); } public SimpleClient(String rootUrl) { this.rootUrl = rootUrl; this.cookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL); // WTF: there is no non-static way to bind a CookieHandler to an // URLConnection! CookieHandler.setDefault(cookies); } public SimpleClient(WebServer ws) { this("http://localhost:"+ws.getPort()); } /** * GETs data from the server at specified path. */ public String get(String path) throws IOException { URL url = new URL(rootUrl + path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(false); // https://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error con.getResponseCode(); InputStream err = con.getErrorStream(); if (err != null) {
byte[] bytes = IO.readFully(err);
pcdv/jflask
jflask/src/main/java/net/jflask/Context.java
// Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // }
import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import net.jflask.util.Log;
package net.jflask; /** * A HTTP handler that receives all requests on a given rootURI and dispatches * them to configured route handlers. * * @author pcdv */ public class Context implements HttpHandler, RequestHandler { private static final String[] EMPTY = {}; private final String rootURI; private final List<MethodHandler> handlers = new ArrayList<>(); final App app; public Context(App app, String rootURI) { this.app = app; this.rootURI = rootURI; } /** * Registers a java method that must be called to process requests matching * specified URI (relative to rootURI). * * @param uri URI schema relative to rootURI (eg. "/:name") * @param m a java method * @param obj the object on which the method must be invoked */ public MethodHandler addHandler(String uri, Route route, Method m, Object obj) {
// Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // } // Path: jflask/src/main/java/net/jflask/Context.java import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import net.jflask.util.Log; package net.jflask; /** * A HTTP handler that receives all requests on a given rootURI and dispatches * them to configured route handlers. * * @author pcdv */ public class Context implements HttpHandler, RequestHandler { private static final String[] EMPTY = {}; private final String rootURI; private final List<MethodHandler> handlers = new ArrayList<>(); final App app; public Context(App app, String rootURI) { this.app = app; this.rootURI = rootURI; } /** * Registers a java method that must be called to process requests matching * specified URI (relative to rootURI). * * @param uri URI schema relative to rootURI (eg. "/:name") * @param m a java method * @param obj the object on which the method must be invoked */ public MethodHandler addHandler(String uri, Route route, Method m, Object obj) {
Log.debug("Add handler for " + route.method() + " on " + rootURI + uri);
pcdv/jflask
jflask/src/main/java/net/jflask/sun/WebServer.java
// Path: jflask/src/main/java/net/jflask/RequestHandler.java // public interface RequestHandler { // App getApp(); // // HttpHandler asHttpHandler(); // }
import java.io.IOException; import java.net.InetSocketAddress; import java.util.Hashtable; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpServer; import net.jflask.RequestHandler;
package net.jflask.sun; /** * Wrapper for the HTTP server embedded in the JDK. It may be shared by several * apps. * * @author pcdv * @see <a * href="http://docs.oracle.com/javase/7/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html">Documentation * for HTTPServer</a> */ public class WebServer { private HttpServer srv; private final ExecutorService pool; private InetSocketAddress address;
// Path: jflask/src/main/java/net/jflask/RequestHandler.java // public interface RequestHandler { // App getApp(); // // HttpHandler asHttpHandler(); // } // Path: jflask/src/main/java/net/jflask/sun/WebServer.java import java.io.IOException; import java.net.InetSocketAddress; import java.util.Hashtable; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpServer; import net.jflask.RequestHandler; package net.jflask.sun; /** * Wrapper for the HTTP server embedded in the JDK. It may be shared by several * apps. * * @author pcdv * @see <a * href="http://docs.oracle.com/javase/7/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html">Documentation * for HTTPServer</a> */ public class WebServer { private HttpServer srv; private final ExecutorService pool; private InetSocketAddress address;
private final Map<String, RequestHandler> handlers = new Hashtable<>();
pcdv/jflask
jflask/src/main/java/net/jflask/MethodHandler.java
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // // Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // }
import java.io.InputStream; import java.lang.reflect.Method; import java.util.Arrays; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO; import net.jflask.util.Log;
res[j++] = i; } if (tok[i].charAt(0) == '*') { if (i != tok.length - 1) throw new IllegalArgumentException("Invalid route: " + rootURI); res[j++] = i; splat = i; } } return Arrays.copyOf(res, j); } /** * @return true when request was handled, false when it was ignored (eg. not * applicable) */ @SuppressWarnings("unchecked") public boolean handle(HttpExchange r, String[] uri, Response resp) throws Exception { if (!isApplicable(r, uri)) return false; if (loginRequired && !ctx.app.checkLoggedIn(r)) { return true; } Object[] args = extractArgs(uri);
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // // Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // } // Path: jflask/src/main/java/net/jflask/MethodHandler.java import java.io.InputStream; import java.lang.reflect.Method; import java.util.Arrays; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO; import net.jflask.util.Log; res[j++] = i; } if (tok[i].charAt(0) == '*') { if (i != tok.length - 1) throw new IllegalArgumentException("Invalid route: " + rootURI); res[j++] = i; splat = i; } } return Arrays.copyOf(res, j); } /** * @return true when request was handled, false when it was ignored (eg. not * applicable) */ @SuppressWarnings("unchecked") public boolean handle(HttpExchange r, String[] uri, Response resp) throws Exception { if (!isApplicable(r, uri)) return false; if (loginRequired && !ctx.app.checkLoggedIn(r)) { return true; } Object[] args = extractArgs(uri);
if (Log.DEBUG)
pcdv/jflask
jflask/src/main/java/net/jflask/MethodHandler.java
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // // Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // }
import java.io.InputStream; import java.lang.reflect.Method; import java.util.Arrays; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO; import net.jflask.util.Log;
Object res = method.invoke(target, args); ctx.app.fireSuccess(method, args, res); return processResponse(r, resp, res); } private boolean processResponse(HttpExchange r, Response resp, Object res) throws Exception { if (converter != null) { converter.convert(res, resp); } else if (converterName != null) { throw new IllegalStateException("Converter '" + converterName + "' not registered in App."); } else if (res instanceof CustomResponse) { // do nothing: status and headers should already be set } else if (res instanceof String) { r.sendResponseHeaders(200, 0); r.getResponseBody().write(((String) res).getBytes("UTF-8")); } else if (res instanceof byte[]) { r.sendResponseHeaders(200, 0); r.getResponseBody().write((byte[]) res); } else if (res instanceof InputStream) { r.sendResponseHeaders(200, 0);
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // // Path: jflask/src/main/java/net/jflask/util/Log.java // public class Log { // // public static final boolean DEBUG = Boolean.getBoolean("debug"); // // public static void warn(Object msg) { // System.err.println("WARN: " + msg); // } // // public static void error(Object msg) { // System.err.println("ERROR: " + msg); // } // // public static void error(Object msg, Throwable t) { // System.err.println("ERROR: " + msg); // t.printStackTrace(); // } // // public static void info(Object msg) { // System.err.println("INFO: " + msg); // } // // public static void debug(Object msg) { // if (DEBUG) // System.err.println("DEBUG: " + msg); // } // // } // Path: jflask/src/main/java/net/jflask/MethodHandler.java import java.io.InputStream; import java.lang.reflect.Method; import java.util.Arrays; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO; import net.jflask.util.Log; Object res = method.invoke(target, args); ctx.app.fireSuccess(method, args, res); return processResponse(r, resp, res); } private boolean processResponse(HttpExchange r, Response resp, Object res) throws Exception { if (converter != null) { converter.convert(res, resp); } else if (converterName != null) { throw new IllegalStateException("Converter '" + converterName + "' not registered in App."); } else if (res instanceof CustomResponse) { // do nothing: status and headers should already be set } else if (res instanceof String) { r.sendResponseHeaders(200, 0); r.getResponseBody().write(((String) res).getBytes("UTF-8")); } else if (res instanceof byte[]) { r.sendResponseHeaders(200, 0); r.getResponseBody().write((byte[]) res); } else if (res instanceof InputStream) { r.sendResponseHeaders(200, 0);
IO.pipe((InputStream) res, r.getResponseBody(), false);