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
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/MovieDetailsActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
package com.tobi.movies.posterdetails; @RunWith(AndroidJUnit4.class) public class MovieDetailsActivityTest { private static final long MOVIE_ID = 293660L; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Such an awesome movie!"; private static final String POSTER_PATH = "deadpool.jpg"; private static final String RELEASE_DATE = "2010-01-01";
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/MovieDetailsActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; package com.tobi.movies.posterdetails; @RunWith(AndroidJUnit4.class) public class MovieDetailsActivityTest { private static final long MOVIE_ID = 293660L; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Such an awesome movie!"; private static final String POSTER_PATH = "deadpool.jpg"; private static final String RELEASE_DATE = "2010-01-01";
private ConfigurableBackend backend;
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/MovieDetailsActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
package com.tobi.movies.posterdetails; @RunWith(AndroidJUnit4.class) public class MovieDetailsActivityTest { private static final long MOVIE_ID = 293660L; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Such an awesome movie!"; private static final String POSTER_PATH = "deadpool.jpg"; private static final String RELEASE_DATE = "2010-01-01"; private ConfigurableBackend backend; private ActivityTestRule<MovieDetailsActivity> rule; private ApiMovieDetails apiMovieDetails; @Before public void setUp() throws Exception {
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/MovieDetailsActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; package com.tobi.movies.posterdetails; @RunWith(AndroidJUnit4.class) public class MovieDetailsActivityTest { private static final long MOVIE_ID = 293660L; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Such an awesome movie!"; private static final String POSTER_PATH = "deadpool.jpg"; private static final String RELEASE_DATE = "2010-01-01"; private ConfigurableBackend backend; private ActivityTestRule<MovieDetailsActivity> rule; private ApiMovieDetails apiMovieDetails; @Before public void setUp() throws Exception {
MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/matchers/PosterMatcher.java
// Path: app/src/main/java/com/tobi/movies/popularstream/MoviePosterAdapter.java // public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.MoviePosterViewHolder> { // // private final List<MoviePoster> moviePosters; // private final ImageLoader imageLoader; // private final Navigator navigator; // // public MoviePosterAdapter(List<MoviePoster> moviePosters, ImageLoader imageLoader, Navigator navigator) { // this.moviePosters = moviePosters; // this.imageLoader = imageLoader; // this.navigator = navigator; // } // // @Override // public MoviePosterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View moviePosterView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_poster, parent, false); // return new MoviePosterViewHolder(moviePosterView); // } // // @Override // public void onBindViewHolder(MoviePosterViewHolder holder, int position) { // final MoviePoster moviePoster = moviePosters.get(position); // String posterPath = moviePoster.getPosterPath(); // imageLoader.loadWebImageInto(Uri.parse(posterPath), holder.posterImage); // holder.posterImage.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // navigator.toMovieDetails(moviePoster.getMovieId()); // } // }); // } // // @Override // public int getItemCount() { // return moviePosters.size(); // } // // @VisibleForTesting // public MoviePoster getItemAt(int position) { // return moviePosters.get(position); // } // // public static class MoviePosterViewHolder extends RecyclerView.ViewHolder { // // @BindView(R.id.posterImage) // ImageView posterImage; // // public MoviePosterViewHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // } // }
import android.support.test.espresso.matcher.BoundedMatcher; import android.support.v7.widget.RecyclerView; import android.view.View; import com.tobi.movies.popularstream.MoviePoster; import com.tobi.movies.popularstream.MoviePosterAdapter; import org.hamcrest.Description; import org.hamcrest.Matcher;
package com.tobi.movies.matchers; public class PosterMatcher { public static Matcher<? super View> hasPosterAt(final int position, final String posterPath) { return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { description.appendText("has poster with path:" + posterPath + " at position:" + position); } @Override protected boolean matchesSafely(RecyclerView item) {
// Path: app/src/main/java/com/tobi/movies/popularstream/MoviePosterAdapter.java // public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.MoviePosterViewHolder> { // // private final List<MoviePoster> moviePosters; // private final ImageLoader imageLoader; // private final Navigator navigator; // // public MoviePosterAdapter(List<MoviePoster> moviePosters, ImageLoader imageLoader, Navigator navigator) { // this.moviePosters = moviePosters; // this.imageLoader = imageLoader; // this.navigator = navigator; // } // // @Override // public MoviePosterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // View moviePosterView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_poster, parent, false); // return new MoviePosterViewHolder(moviePosterView); // } // // @Override // public void onBindViewHolder(MoviePosterViewHolder holder, int position) { // final MoviePoster moviePoster = moviePosters.get(position); // String posterPath = moviePoster.getPosterPath(); // imageLoader.loadWebImageInto(Uri.parse(posterPath), holder.posterImage); // holder.posterImage.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // navigator.toMovieDetails(moviePoster.getMovieId()); // } // }); // } // // @Override // public int getItemCount() { // return moviePosters.size(); // } // // @VisibleForTesting // public MoviePoster getItemAt(int position) { // return moviePosters.get(position); // } // // public static class MoviePosterViewHolder extends RecyclerView.ViewHolder { // // @BindView(R.id.posterImage) // ImageView posterImage; // // public MoviePosterViewHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // } // } // Path: app/src/androidTest/java/com/tobi/movies/matchers/PosterMatcher.java import android.support.test.espresso.matcher.BoundedMatcher; import android.support.v7.widget.RecyclerView; import android.view.View; import com.tobi.movies.popularstream.MoviePoster; import com.tobi.movies.popularstream.MoviePosterAdapter; import org.hamcrest.Description; import org.hamcrest.Matcher; package com.tobi.movies.matchers; public class PosterMatcher { public static Matcher<? super View> hasPosterAt(final int position, final String posterPath) { return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { @Override public void describeTo(Description description) { description.appendText("has poster with path:" + posterPath + " at position:" + position); } @Override protected boolean matchesSafely(RecyclerView item) {
MoviePosterAdapter adapter = (MoviePosterAdapter) item.getAdapter();
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/MoviePosterAdapter.java
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // }
import android.net.Uri; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.tobi.movies.ImageLoader; import com.tobi.movies.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package com.tobi.movies.popularstream; public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.MoviePosterViewHolder> { private final List<MoviePoster> moviePosters;
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // Path: app/src/main/java/com/tobi/movies/popularstream/MoviePosterAdapter.java import android.net.Uri; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.tobi.movies.ImageLoader; import com.tobi.movies.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package com.tobi.movies.popularstream; public class MoviePosterAdapter extends RecyclerView.Adapter<MoviePosterAdapter.MoviePosterViewHolder> { private final List<MoviePoster> moviePosters;
private final ImageLoader imageLoader;
tobiasheine/Movies
app/src/main/java/com/tobi/movies/misc/ImageModule.java
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // }
import com.tobi.movies.ImageLoader; import dagger.Module; import dagger.Provides;
package com.tobi.movies.misc; @Module public class ImageModule { @Provides
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java import com.tobi.movies.ImageLoader; import dagger.Module; import dagger.Provides; package com.tobi.movies.misc; @Module public class ImageModule { @Provides
ImageLoader provideImageLoader() {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/utils/CucumberInstrumentation.java
// Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java // public class TestMovieApplication extends MovieApplication { // // @Override // protected ApplicationComponent applicationComponent() { // return DaggerTestApplicationComponent.create(); // } // // @Override // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerTestPopularMoviesComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // // @Override // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerTestMovieDetailsComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // }
import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.runner.AndroidJUnitRunner; import com.tobi.movies.BuildConfig; import com.tobi.movies.TestMovieApplication; import cucumber.api.android.CucumberInstrumentationCore;
public void onCreate(final Bundle bundle) { String tags = BuildConfig.TEST_TAGS; if (!tags.isEmpty()) { String tagsKey = tags.replaceAll("\\s", ""); bundle.putString(CUCUMBER_TAGS_KEY, tagsKey); } String scenario = BuildConfig.TEST_SCENARIO; if (!scenario.isEmpty()) { scenario = scenario.replaceAll(" ", "\\\\s"); bundle.putString(CUCUMBER_SCENARIO_KEY, scenario); } String feature = BuildConfig.TEST_FEATURE; if (!feature.isEmpty()) { bundle.putString(CUCUMBER_FEATURE_KEY, feature); } instrumentationCore.create(bundle); super.onCreate(bundle); } @Override public void onStart() { waitForIdleSync(); instrumentationCore.start(); } @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java // public class TestMovieApplication extends MovieApplication { // // @Override // protected ApplicationComponent applicationComponent() { // return DaggerTestApplicationComponent.create(); // } // // @Override // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerTestPopularMoviesComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // // @Override // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerTestMovieDetailsComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // } // Path: app/src/androidTest/java/com/tobi/movies/utils/CucumberInstrumentation.java import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.runner.AndroidJUnitRunner; import com.tobi.movies.BuildConfig; import com.tobi.movies.TestMovieApplication; import cucumber.api.android.CucumberInstrumentationCore; public void onCreate(final Bundle bundle) { String tags = BuildConfig.TEST_TAGS; if (!tags.isEmpty()) { String tagsKey = tags.replaceAll("\\s", ""); bundle.putString(CUCUMBER_TAGS_KEY, tagsKey); } String scenario = BuildConfig.TEST_SCENARIO; if (!scenario.isEmpty()) { scenario = scenario.replaceAll(" ", "\\\\s"); bundle.putString(CUCUMBER_SCENARIO_KEY, scenario); } String feature = BuildConfig.TEST_FEATURE; if (!feature.isEmpty()) { bundle.putString(CUCUMBER_FEATURE_KEY, feature); } instrumentationCore.create(bundle); super.onCreate(bundle); } @Override public void onStart() { waitForIdleSync(); instrumentationCore.start(); } @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String testAppClassName = TestMovieApplication.class.getCanonicalName();
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = {
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = {
ImageModule.class,
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, StreamApiModule.class, StreamConverterModule.class,
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, StreamApiModule.class, StreamConverterModule.class,
ThreadingModule.class
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, StreamApiModule.class, StreamConverterModule.class, ThreadingModule.class },
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, StreamApiModule.class, StreamConverterModule.class, ThreadingModule.class },
dependencies = ApplicationComponent.class
tobiasheine/Movies
app/src/test/java/com/tobi/movies/popularstream/PopularStreamRepositoryTest.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.support.annotation.NonNull; import com.google.common.collect.Lists; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import java.util.HashMap; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import rx.Observable; import rx.Scheduler; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import static org.mockito.Mockito.when;
package com.tobi.movies.popularstream; public class PopularStreamRepositoryTest { private static final long FIRST_MOVIE_ID = 1L; private static final long SECOND_MOVIE_ID = 2L; private static final String FIRST_POSTER_PATH = "first path"; private static final String SECOND_POSTER_PATH = "second path"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private PopularStreamApiDatasource apiDataSource; @Mock
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/test/java/com/tobi/movies/popularstream/PopularStreamRepositoryTest.java import android.support.annotation.NonNull; import com.google.common.collect.Lists; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import java.util.HashMap; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import rx.Observable; import rx.Scheduler; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import static org.mockito.Mockito.when; package com.tobi.movies.popularstream; public class PopularStreamRepositoryTest { private static final long FIRST_MOVIE_ID = 1L; private static final long SECOND_MOVIE_ID = 2L; private static final String FIRST_POSTER_PATH = "first path"; private static final String SECOND_POSTER_PATH = "second path"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private PopularStreamApiDatasource apiDataSource; @Mock
private Converter<ApiMoviePoster, MoviePoster> posterConverter;
tobiasheine/Movies
app/src/test/java/com/tobi/movies/popularstream/PopularStreamRepositoryTest.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.support.annotation.NonNull; import com.google.common.collect.Lists; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import java.util.HashMap; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import rx.Observable; import rx.Scheduler; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import static org.mockito.Mockito.when;
package com.tobi.movies.popularstream; public class PopularStreamRepositoryTest { private static final long FIRST_MOVIE_ID = 1L; private static final long SECOND_MOVIE_ID = 2L; private static final String FIRST_POSTER_PATH = "first path"; private static final String SECOND_POSTER_PATH = "second path"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private PopularStreamApiDatasource apiDataSource; @Mock private Converter<ApiMoviePoster, MoviePoster> posterConverter; private PopularStreamRepository streamRepository; @Before public void setUp() throws Exception {
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/test/java/com/tobi/movies/popularstream/PopularStreamRepositoryTest.java import android.support.annotation.NonNull; import com.google.common.collect.Lists; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import java.util.HashMap; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import rx.Observable; import rx.Scheduler; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import static org.mockito.Mockito.when; package com.tobi.movies.popularstream; public class PopularStreamRepositoryTest { private static final long FIRST_MOVIE_ID = 1L; private static final long SECOND_MOVIE_ID = 2L; private static final String FIRST_POSTER_PATH = "first path"; private static final String SECOND_POSTER_PATH = "second path"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private PopularStreamApiDatasource apiDataSource; @Mock private Converter<ApiMoviePoster, MoviePoster> posterConverter; private PopularStreamRepository streamRepository; @Before public void setUp() throws Exception {
HashMap<Threading, Scheduler> schedulerHashMap = new HashMap<>();
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler;
package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler; package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject
ImageLoader imageLoader;
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler;
package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject ImageLoader imageLoader; @Inject
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler; package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject ImageLoader imageLoader; @Inject
Map<Threading, Scheduler> schedulerMap;
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler;
package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject ImageLoader imageLoader; @Inject Map<Threading, Scheduler> schedulerMap; @Inject MovieDetailsRepository movieDetailsRepository; private MovieDetailsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); ButterKnife.bind(this);
// Path: app/src/main/java/com/tobi/movies/ImageLoader.java // public class ImageLoader { // // public void loadWebImageInto(Uri imageUrl, ImageView imageView) { // Glide // .with(imageView.getContext()) // .load(imageUrl) // .crossFade() // .into(imageView); // } // } // // Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.tobi.movies.ImageLoader; import com.tobi.movies.MovieApplication; import com.tobi.movies.R; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import rx.Scheduler; package com.tobi.movies.posterdetails; public class MovieDetailsActivity extends Activity implements MovieDetailsMVP.View { private static final String EXTRA_MOVIE_ID = "extra_movie_id"; private MovieDetailsUseCase movieDetailsUseCase; public static Intent createIntentFor(long movieId, Context activity) { Intent intent = new Intent(activity, MovieDetailsActivity.class); intent.putExtra(EXTRA_MOVIE_ID, movieId); return intent; } @BindView(R.id.movieTitle) TextView movieTitle; @BindView(R.id.posterImage) ImageView moviePoster; @BindView(R.id.movieOverview) TextView movieOverview; @Inject ImageLoader imageLoader; @Inject Map<Threading, Scheduler> schedulerMap; @Inject MovieDetailsRepository movieDetailsRepository; private MovieDetailsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); ButterKnife.bind(this);
MovieApplication application = (MovieApplication) getApplication();
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/PopularStreamRepository.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.support.annotation.NonNull; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.Observable; import rx.Scheduler; import rx.functions.Func1;
package com.tobi.movies.popularstream; public class PopularStreamRepository { private final PopularStreamApiDatasource popularStreamApiDatasource; private final Scheduler subscribeScheduler; private final Scheduler observeScheduler;
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/main/java/com/tobi/movies/popularstream/PopularStreamRepository.java import android.support.annotation.NonNull; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.Observable; import rx.Scheduler; import rx.functions.Func1; package com.tobi.movies.popularstream; public class PopularStreamRepository { private final PopularStreamApiDatasource popularStreamApiDatasource; private final Scheduler subscribeScheduler; private final Scheduler observeScheduler;
private final Converter<ApiMoviePoster, MoviePoster> posterConverter;
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/PopularStreamRepository.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // }
import android.support.annotation.NonNull; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.Observable; import rx.Scheduler; import rx.functions.Func1;
package com.tobi.movies.popularstream; public class PopularStreamRepository { private final PopularStreamApiDatasource popularStreamApiDatasource; private final Scheduler subscribeScheduler; private final Scheduler observeScheduler; private final Converter<ApiMoviePoster, MoviePoster> posterConverter; @Inject public PopularStreamRepository(PopularStreamApiDatasource popularStreamApiDatasource,
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // // Path: app/src/main/java/com/tobi/movies/misc/Threading.java // public enum Threading { // SUBSCRIBER, // OBSERVER // } // Path: app/src/main/java/com/tobi/movies/popularstream/PopularStreamRepository.java import android.support.annotation.NonNull; import com.tobi.movies.Converter; import com.tobi.movies.misc.Threading; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.Map; import rx.Observable; import rx.Scheduler; import rx.functions.Func1; package com.tobi.movies.popularstream; public class PopularStreamRepository { private final PopularStreamApiDatasource popularStreamApiDatasource; private final Scheduler subscribeScheduler; private final Scheduler observeScheduler; private final Converter<ApiMoviePoster, MoviePoster> posterConverter; @Inject public PopularStreamRepository(PopularStreamApiDatasource popularStreamApiDatasource,
Map<Threading, Scheduler> schedulerMap,
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // }
import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After;
package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend();
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // } // Path: app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After; package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend();
ActivityFinisher.finishOpenActivities();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // }
import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After;
package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() {
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // } // Path: app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After; package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() {
MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // }
import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After;
package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // } // Path: app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After; package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
ConfigurableBackend backend = (ConfigurableBackend) ((TestPopularMoviesComponent) movieApplication.getPopularMoviesComponent()).backend();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // }
import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After;
package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // TestStreamConverterModule.class, // TestStreamApiModule.class, // TestThreadingModule.class, // }, // dependencies = TestApplicationComponent.class // ) // public interface TestPopularMoviesComponent extends PopularMoviesComponent { // Backend backend(); // } // // Path: app/src/androidTest/java/com/tobi/movies/utils/ActivityFinisher.java // public class ActivityFinisher implements Runnable { // // public static void finishOpenActivities() { // new Handler(Looper.getMainLooper()).post(new ActivityFinisher()); // } // // private final ActivityLifecycleMonitor activityLifecycleMonitor; // // private ActivityFinisher() { // this.activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); // } // // @Override // public void run() { // final List<Activity> activities = new ArrayList<>(); // // for (final Stage stage : EnumSet.range(Stage.CREATED, Stage.STOPPED)) { // activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)); // } // // for (final Activity activity : activities) { // if (!activity.isFinishing()) { // activity.finish(); // } // } // } // } // Path: app/src/androidTest/java/com/tobi/movies/steps/SetupSteps.java import android.support.test.InstrumentationRegistry; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.popularstream.TestPopularMoviesComponent; import com.tobi.movies.utils.ActivityFinisher; import cucumber.api.java.After; package com.tobi.movies.steps; public class SetupSteps { @After public void tearDown() { clearBackend(); ActivityFinisher.finishOpenActivities(); } private void clearBackend() { MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
ConfigurableBackend backend = (ConfigurableBackend) ((TestPopularMoviesComponent) movieApplication.getPopularMoviesComponent()).backend();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/TestStreamConverterModule.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // }
import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides;
package com.tobi.movies.popularstream; @Module class TestStreamConverterModule { @Provides
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestStreamConverterModule.java import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides; package com.tobi.movies.popularstream; @Module class TestStreamConverterModule { @Provides
Converter<ApiMoviePoster, MoviePoster> provideStreamConverter() {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = {
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = {
ImageModule.class,
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { ImageModule.class, TestDetailsApiModule.class,
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { ImageModule.class, TestDetailsApiModule.class,
TestThreadingModule.class,
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { ImageModule.class, TestDetailsApiModule.class, TestThreadingModule.class, TestDetailsConverterModule.class },
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/TestMovieDetailsComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { ImageModule.class, TestDetailsApiModule.class, TestThreadingModule.class, TestDetailsConverterModule.class },
dependencies = TestApplicationComponent.class
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule;
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule;
private ConfigurableBackend backend;
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule; private ConfigurableBackend backend; private ApiMoviePoster apiMoviePoster;
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule; private ConfigurableBackend backend; private ApiMoviePoster apiMoviePoster;
private ApiMovieDetails movieDetails;
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule; private ConfigurableBackend backend; private ApiMoviePoster apiMoviePoster; private ApiMovieDetails movieDetails; @Before public void setUp() throws Exception {
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; package com.tobi.movies.popularstream; @RunWith(AndroidJUnit4.class) public class PopularMoviesActivityTest { private static final long MOVIE_ID = 293660L; private static final String POSTER_PATH = "deadpool.jpg"; private static final String MOVIE_TITLE = "Deadpool"; private static final String MOVIE_DESCRIPTION = "Awesome movie"; private static final String RELEASE_DATE = "2000-01-01"; private ActivityTestRule<PopularMoviesActivity> rule; private ConfigurableBackend backend; private ApiMoviePoster apiMoviePoster; private ApiMovieDetails movieDetails; @Before public void setUp() throws Exception {
MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
rule = new ActivityTestRule<>(PopularMoviesActivity.class); apiMoviePoster = createApiMoviePoster(MOVIE_ID, POSTER_PATH); movieDetails = createMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE); } @After public void tearDown() throws Exception { backend.clear(); } @Test public void shouldShowPoster() throws Exception { backend.addToPopularStream(apiMoviePoster); PopularMoviesRobot .create() .launchPopularMovies(rule) .checkPosterWithPathIsDisplayedAtPosition(0, POSTER_PATH); } @Test public void shouldNavigateToMovieDetails() throws Exception { backend.addToPopularStream(apiMoviePoster); backend.addMovieDetails(movieDetails); PopularMoviesRobot .create() .launchPopularMovies(rule) .selectPosterAtPosition(0)
// Path: app/src/main/java/com/tobi/movies/MovieApplication.java // public class MovieApplication extends Application { // // private PopularMoviesComponent popularMoviesComponent; // private MovieDetailsComponent movieDetailsComponent; // // @Override // public void onCreate() { // super.onCreate(); // ApplicationComponent applicationComponent = applicationComponent(); // popularMoviesComponent = popularMoviesComponent(applicationComponent); // movieDetailsComponent = movieDetailsComponent(applicationComponent); // } // // protected ApplicationComponent applicationComponent() { // return DaggerApplicationComponent.create(); // } // // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerMovieDetailsComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerPopularMoviesComponent.builder() // .applicationComponent(applicationComponent) // .build(); // } // // public PopularMoviesComponent getPopularMoviesComponent() { // return popularMoviesComponent; // } // // public MovieDetailsComponent getMovieDetailsComponent() { // return movieDetailsComponent; // } // } // // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java // public class ConfigurableBackend implements Backend { // // private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); // private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); // // public void addMovieDetails(ApiMovieDetails apiMovieDetails) { // movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); // } // // public void addToPopularStream(ApiMoviePoster movieDetails) { // popularStream.add(movieDetails); // } // // @Override // public Observable<ApiPopularMoviesResponse> popularStream() { // return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { // @Override // public ApiPopularMoviesResponse call() throws Exception { // return new PublicApiPopularMoviesResponse(popularStream); // } // }); // } // // @Override // public Observable<ApiMovieDetails> movieDetails(@Path("id") final long movieId) { // return Observable.fromCallable(new Callable<ApiMovieDetails>() { // @Override // public ApiMovieDetails call() throws Exception { // return movieDetails.get(movieId); // } // }); // } // // public void clear() { // movieDetails.clear(); // popularStream.clear(); // } // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/PosterDetailsRobot.java // public class PosterDetailsRobot extends Robot<PosterDetailsRobot> { // // public static PosterDetailsRobot create() { // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot() { // } // // public PosterDetailsRobot checkMovieTitleIsDisplayed(String movieTitle) { // return checkTextIsDisplayed(movieTitle, R.id.movieTitle); // } // // public PosterDetailsRobot launchDetailsScreen(long movieId, ActivityTestRule<MovieDetailsActivity> testRule) { // testRule.launchActivity(MovieDetailsActivity.createIntentFor(movieId, InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getApplicationContext())); // return new PosterDetailsRobot(); // } // // public PosterDetailsRobot checkMovieDescriptionIsDisplayed(String movieDescription) { // return checkTextIsDisplayed(movieDescription, R.id.movieOverview); // } // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesActivityTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import com.tobi.movies.MovieApplication; import com.tobi.movies.backend.ConfigurableBackend; import com.tobi.movies.posterdetails.ApiMovieDetails; import com.tobi.movies.posterdetails.PosterDetailsRobot; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; rule = new ActivityTestRule<>(PopularMoviesActivity.class); apiMoviePoster = createApiMoviePoster(MOVIE_ID, POSTER_PATH); movieDetails = createMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE); } @After public void tearDown() throws Exception { backend.clear(); } @Test public void shouldShowPoster() throws Exception { backend.addToPopularStream(apiMoviePoster); PopularMoviesRobot .create() .launchPopularMovies(rule) .checkPosterWithPathIsDisplayedAtPosition(0, POSTER_PATH); } @Test public void shouldNavigateToMovieDetails() throws Exception { backend.addToPopularStream(apiMoviePoster); backend.addMovieDetails(movieDetails); PopularMoviesRobot .create() .launchPopularMovies(rule) .selectPosterAtPosition(0)
.toRobot(PosterDetailsRobot.class)
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class,
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class,
ImageModule.class,
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class, ImageModule.class,
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class, ImageModule.class,
ThreadingModule.class
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component;
package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class, ImageModule.class, ThreadingModule.class },
// Path: app/src/main/java/com/tobi/movies/ApplicationComponent.java // @ApplicationScope // @Component(modules = BackendModule.class) // public interface ApplicationComponent { // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/main/java/com/tobi/movies/misc/ThreadingModule.java // @Module // public class ThreadingModule { // // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // @Provides // Scheduler provideSubscriberScheduler() { // return Schedulers.io(); // } // // @IntoMap // @ThreadingKey(Threading.OBSERVER) // @Provides // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java import com.tobi.movies.ApplicationComponent; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.ThreadingModule; import dagger.Component; package com.tobi.movies.posterdetails; @ActivityScope @Component( modules = { DetailsConverterModule.class, DetailsApiModule.class, ImageModule.class, ThreadingModule.class },
dependencies = ApplicationComponent.class
tobiasheine/Movies
app/src/main/java/com/tobi/movies/MovieApplication.java
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // }
import android.app.Application; import com.tobi.movies.popularstream.DaggerPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent;
package com.tobi.movies; public class MovieApplication extends Application { private PopularMoviesComponent popularMoviesComponent;
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // } // Path: app/src/main/java/com/tobi/movies/MovieApplication.java import android.app.Application; import com.tobi.movies.popularstream.DaggerPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent; package com.tobi.movies; public class MovieApplication extends Application { private PopularMoviesComponent popularMoviesComponent;
private MovieDetailsComponent movieDetailsComponent;
tobiasheine/Movies
app/src/main/java/com/tobi/movies/popularstream/StreamConverterModule.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // }
import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides;
package com.tobi.movies.popularstream; @Module class StreamConverterModule { @Provides
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // Path: app/src/main/java/com/tobi/movies/popularstream/StreamConverterModule.java import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides; package com.tobi.movies.popularstream; @Module class StreamConverterModule { @Provides
Converter<ApiMoviePoster, MoviePoster> providePosterConverter() {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/runner/DaggerOverridesTestRunner.java
// Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java // public class TestMovieApplication extends MovieApplication { // // @Override // protected ApplicationComponent applicationComponent() { // return DaggerTestApplicationComponent.create(); // } // // @Override // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerTestPopularMoviesComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // // @Override // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerTestMovieDetailsComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // }
import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.tobi.movies.TestMovieApplication;
package com.tobi.movies.runner; public class DaggerOverridesTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java // public class TestMovieApplication extends MovieApplication { // // @Override // protected ApplicationComponent applicationComponent() { // return DaggerTestApplicationComponent.create(); // } // // @Override // protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { // return DaggerTestPopularMoviesComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // // @Override // protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) { // return DaggerTestMovieDetailsComponent.builder() // .testApplicationComponent((TestApplicationComponent) applicationComponent) // .build(); // } // } // Path: app/src/androidTest/java/com/tobi/movies/runner/DaggerOverridesTestRunner.java import android.app.Application; import android.content.Context; import android.support.test.runner.AndroidJUnitRunner; import com.tobi.movies.TestMovieApplication; package com.tobi.movies.runner; public class DaggerOverridesTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String testAppClassName = TestMovieApplication.class.getCanonicalName();
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java
// Path: base/src/main/java/com/tobi/movies/popularstream/ApiPopularMoviesResponse.java // public class ApiPopularMoviesResponse { // // @SerializedName("results") // List<ApiMoviePoster> results; // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PublicApiPopularMoviesResponse.java // public class PublicApiPopularMoviesResponse extends ApiPopularMoviesResponse { // // public PublicApiPopularMoviesResponse(List<ApiMoviePoster> results) { // this.results = results; // } // // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // }
import android.support.test.espresso.core.deps.guava.collect.Lists; import com.tobi.movies.popularstream.ApiMoviePoster; import com.tobi.movies.popularstream.ApiPopularMoviesResponse; import com.tobi.movies.popularstream.PublicApiPopularMoviesResponse; import com.tobi.movies.posterdetails.ApiMovieDetails; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import retrofit2.http.Path; import rx.Observable;
package com.tobi.movies.backend; public class ConfigurableBackend implements Backend { private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); public void addMovieDetails(ApiMovieDetails apiMovieDetails) { movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); } public void addToPopularStream(ApiMoviePoster movieDetails) { popularStream.add(movieDetails); } @Override
// Path: base/src/main/java/com/tobi/movies/popularstream/ApiPopularMoviesResponse.java // public class ApiPopularMoviesResponse { // // @SerializedName("results") // List<ApiMoviePoster> results; // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PublicApiPopularMoviesResponse.java // public class PublicApiPopularMoviesResponse extends ApiPopularMoviesResponse { // // public PublicApiPopularMoviesResponse(List<ApiMoviePoster> results) { // this.results = results; // } // // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java import android.support.test.espresso.core.deps.guava.collect.Lists; import com.tobi.movies.popularstream.ApiMoviePoster; import com.tobi.movies.popularstream.ApiPopularMoviesResponse; import com.tobi.movies.popularstream.PublicApiPopularMoviesResponse; import com.tobi.movies.posterdetails.ApiMovieDetails; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import retrofit2.http.Path; import rx.Observable; package com.tobi.movies.backend; public class ConfigurableBackend implements Backend { private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); public void addMovieDetails(ApiMovieDetails apiMovieDetails) { movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); } public void addToPopularStream(ApiMoviePoster movieDetails) { popularStream.add(movieDetails); } @Override
public Observable<ApiPopularMoviesResponse> popularStream() {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java
// Path: base/src/main/java/com/tobi/movies/popularstream/ApiPopularMoviesResponse.java // public class ApiPopularMoviesResponse { // // @SerializedName("results") // List<ApiMoviePoster> results; // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PublicApiPopularMoviesResponse.java // public class PublicApiPopularMoviesResponse extends ApiPopularMoviesResponse { // // public PublicApiPopularMoviesResponse(List<ApiMoviePoster> results) { // this.results = results; // } // // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // }
import android.support.test.espresso.core.deps.guava.collect.Lists; import com.tobi.movies.popularstream.ApiMoviePoster; import com.tobi.movies.popularstream.ApiPopularMoviesResponse; import com.tobi.movies.popularstream.PublicApiPopularMoviesResponse; import com.tobi.movies.posterdetails.ApiMovieDetails; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import retrofit2.http.Path; import rx.Observable;
package com.tobi.movies.backend; public class ConfigurableBackend implements Backend { private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); public void addMovieDetails(ApiMovieDetails apiMovieDetails) { movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); } public void addToPopularStream(ApiMoviePoster movieDetails) { popularStream.add(movieDetails); } @Override public Observable<ApiPopularMoviesResponse> popularStream() { return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { @Override public ApiPopularMoviesResponse call() throws Exception {
// Path: base/src/main/java/com/tobi/movies/popularstream/ApiPopularMoviesResponse.java // public class ApiPopularMoviesResponse { // // @SerializedName("results") // List<ApiMoviePoster> results; // } // // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PublicApiPopularMoviesResponse.java // public class PublicApiPopularMoviesResponse extends ApiPopularMoviesResponse { // // public PublicApiPopularMoviesResponse(List<ApiMoviePoster> results) { // this.results = results; // } // // } // // Path: base/src/main/java/com/tobi/movies/posterdetails/ApiMovieDetails.java // public class ApiMovieDetails { // // @SerializedName("id") // public long movieId; // // @SerializedName("poster_path") // public String posterPath; // // @SerializedName("original_title") // public String originalTitle; // // @SerializedName("overview") // public String overview; // // @SerializedName("release_date") // public String releaseDate; // } // Path: app/src/androidTest/java/com/tobi/movies/backend/ConfigurableBackend.java import android.support.test.espresso.core.deps.guava.collect.Lists; import com.tobi.movies.popularstream.ApiMoviePoster; import com.tobi.movies.popularstream.ApiPopularMoviesResponse; import com.tobi.movies.popularstream.PublicApiPopularMoviesResponse; import com.tobi.movies.posterdetails.ApiMovieDetails; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import retrofit2.http.Path; import rx.Observable; package com.tobi.movies.backend; public class ConfigurableBackend implements Backend { private final Map<Long, ApiMovieDetails> movieDetails = new HashMap<>(); private final List<ApiMoviePoster> popularStream = Lists.newArrayList(); public void addMovieDetails(ApiMovieDetails apiMovieDetails) { movieDetails.put(apiMovieDetails.movieId, apiMovieDetails); } public void addToPopularStream(ApiMoviePoster movieDetails) { popularStream.add(movieDetails); } @Override public Observable<ApiPopularMoviesResponse> popularStream() { return Observable.fromCallable(new Callable<ApiPopularMoviesResponse>() { @Override public ApiPopularMoviesResponse call() throws Exception {
return new PublicApiPopularMoviesResponse(popularStream);
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // }
import com.tobi.movies.popularstream.DaggerTestPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerTestMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent;
package com.tobi.movies; public class TestMovieApplication extends MovieApplication { @Override protected ApplicationComponent applicationComponent() { return DaggerTestApplicationComponent.create(); } @Override
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // } // Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java import com.tobi.movies.popularstream.DaggerTestPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerTestMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent; package com.tobi.movies; public class TestMovieApplication extends MovieApplication { @Override protected ApplicationComponent applicationComponent() { return DaggerTestApplicationComponent.create(); } @Override
protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // }
import com.tobi.movies.popularstream.DaggerTestPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerTestMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent;
package com.tobi.movies; public class TestMovieApplication extends MovieApplication { @Override protected ApplicationComponent applicationComponent() { return DaggerTestApplicationComponent.create(); } @Override protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { return DaggerTestPopularMoviesComponent.builder() .testApplicationComponent((TestApplicationComponent) applicationComponent) .build(); } @Override
// Path: app/src/main/java/com/tobi/movies/popularstream/PopularMoviesComponent.java // @ActivityScope // @Component( // modules = { // ImageModule.class, // StreamApiModule.class, // StreamConverterModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface PopularMoviesComponent { // // void inject(PopularMoviesActivity popularMoviesActivity); // } // // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsComponent.java // @ActivityScope // @Component( // modules = { // DetailsConverterModule.class, // DetailsApiModule.class, // ImageModule.class, // ThreadingModule.class // }, // dependencies = ApplicationComponent.class // ) // public interface MovieDetailsComponent { // void inject(MovieDetailsActivity movieDetailsActivity); // } // Path: app/src/androidTest/java/com/tobi/movies/TestMovieApplication.java import com.tobi.movies.popularstream.DaggerTestPopularMoviesComponent; import com.tobi.movies.popularstream.PopularMoviesComponent; import com.tobi.movies.posterdetails.DaggerTestMovieDetailsComponent; import com.tobi.movies.posterdetails.MovieDetailsComponent; package com.tobi.movies; public class TestMovieApplication extends MovieApplication { @Override protected ApplicationComponent applicationComponent() { return DaggerTestApplicationComponent.create(); } @Override protected PopularMoviesComponent popularMoviesComponent(ApplicationComponent applicationComponent) { return DaggerTestPopularMoviesComponent.builder() .testApplicationComponent((TestApplicationComponent) applicationComponent) .build(); } @Override
protected MovieDetailsComponent movieDetailsComponent(ApplicationComponent applicationComponent) {
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/DetailsApiModule.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // }
import com.tobi.movies.Converter; import com.tobi.movies.backend.Backend; import dagger.Module; import dagger.Provides;
package com.tobi.movies.posterdetails; @Module() class DetailsApiModule { @Provides MovieDetailsApiDatasource provideDetailsApiSource(Backend backend) { return new MovieDetailsApiDatasource(backend); } @Provides MovieDetailsRepository providesDetailsRepository(MovieDetailsApiDatasource apiDatasource,
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // Path: app/src/main/java/com/tobi/movies/posterdetails/DetailsApiModule.java import com.tobi.movies.Converter; import com.tobi.movies.backend.Backend; import dagger.Module; import dagger.Provides; package com.tobi.movies.posterdetails; @Module() class DetailsApiModule { @Provides MovieDetailsApiDatasource provideDetailsApiSource(Backend backend) { return new MovieDetailsApiDatasource(backend); } @Provides MovieDetailsRepository providesDetailsRepository(MovieDetailsApiDatasource apiDatasource,
Converter<ApiMovieDetails, MovieDetails> converter) {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/posterdetails/TestDetailsConverterModule.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // }
import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides;
package com.tobi.movies.posterdetails; @Module class TestDetailsConverterModule { @Provides
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // Path: app/src/androidTest/java/com/tobi/movies/posterdetails/TestDetailsConverterModule.java import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides; package com.tobi.movies.posterdetails; @Module class TestDetailsConverterModule { @Provides
Converter<ApiMovieDetails, MovieDetails> provideDetailsConverter() {
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesRobot.java
// Path: app/src/androidTest/java/com/tobi/movies/Robot.java // public abstract class Robot<T extends Robot> { // // protected T checkTextIsDisplayed(String text, @IdRes int view) { // onView(allOf(withId(view), withText(text))).check(matches(isDisplayed())); // return (T) this; // } // // protected T selectPositionInRecyclerView(int position, @IdRes int recyclerView) { // onView(withId(recyclerView)) // .perform(RecyclerViewActions.actionOnItemAtPosition(position, click())); // return (T) this; // } // // public T waitFor(int seconds) throws InterruptedException { // Thread.sleep(seconds * 1000); // return (T) this; // } // // // public <K> K toRobot(Class<K> robotClass) throws IllegalAccessException, InstantiationException { // return robotClass.newInstance(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/matchers/PosterMatcher.java // public class PosterMatcher { // // public static Matcher<? super View> hasPosterAt(final int position, final String posterPath) { // return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { // @Override // public void describeTo(Description description) { // description.appendText("has poster with path:" + posterPath + " at position:" + position); // } // // @Override // protected boolean matchesSafely(RecyclerView item) { // MoviePosterAdapter adapter = (MoviePosterAdapter) item.getAdapter(); // MoviePoster moviePoster = adapter.getItemAt(position); // return moviePoster.getPosterPath().contains(posterPath); // } // }; // } // }
import android.support.test.rule.ActivityTestRule; import com.tobi.movies.R; import com.tobi.movies.Robot; import com.tobi.movies.matchers.PosterMatcher; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId;
package com.tobi.movies.popularstream; public class PopularMoviesRobot extends Robot<PopularMoviesRobot> { public static PopularMoviesRobot create() { return new PopularMoviesRobot(); } public PopularMoviesRobot() { } public PopularMoviesRobot launchPopularMovies(ActivityTestRule<PopularMoviesActivity> rule) { rule.launchActivity(null); return this; } public PopularMoviesRobot checkPosterWithPathIsDisplayedAtPosition(int position, String posterPath) { onView(withId(R.id.popularMovies_recycler))
// Path: app/src/androidTest/java/com/tobi/movies/Robot.java // public abstract class Robot<T extends Robot> { // // protected T checkTextIsDisplayed(String text, @IdRes int view) { // onView(allOf(withId(view), withText(text))).check(matches(isDisplayed())); // return (T) this; // } // // protected T selectPositionInRecyclerView(int position, @IdRes int recyclerView) { // onView(withId(recyclerView)) // .perform(RecyclerViewActions.actionOnItemAtPosition(position, click())); // return (T) this; // } // // public T waitFor(int seconds) throws InterruptedException { // Thread.sleep(seconds * 1000); // return (T) this; // } // // // public <K> K toRobot(Class<K> robotClass) throws IllegalAccessException, InstantiationException { // return robotClass.newInstance(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/matchers/PosterMatcher.java // public class PosterMatcher { // // public static Matcher<? super View> hasPosterAt(final int position, final String posterPath) { // return new BoundedMatcher<View, RecyclerView>(RecyclerView.class) { // @Override // public void describeTo(Description description) { // description.appendText("has poster with path:" + posterPath + " at position:" + position); // } // // @Override // protected boolean matchesSafely(RecyclerView item) { // MoviePosterAdapter adapter = (MoviePosterAdapter) item.getAdapter(); // MoviePoster moviePoster = adapter.getItemAt(position); // return moviePoster.getPosterPath().contains(posterPath); // } // }; // } // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/PopularMoviesRobot.java import android.support.test.rule.ActivityTestRule; import com.tobi.movies.R; import com.tobi.movies.Robot; import com.tobi.movies.matchers.PosterMatcher; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; package com.tobi.movies.popularstream; public class PopularMoviesRobot extends Robot<PopularMoviesRobot> { public static PopularMoviesRobot create() { return new PopularMoviesRobot(); } public PopularMoviesRobot() { } public PopularMoviesRobot launchPopularMovies(ActivityTestRule<PopularMoviesActivity> rule) { rule.launchActivity(null); return this; } public PopularMoviesRobot checkPosterWithPathIsDisplayedAtPosition(int position, String posterPath) { onView(withId(R.id.popularMovies_recycler))
.check(matches(PosterMatcher.hasPosterAt(position, posterPath)));
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = {
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = {
ImageModule.class,
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, TestStreamConverterModule.class, TestStreamApiModule.class,
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, TestStreamConverterModule.class, TestStreamApiModule.class,
TestThreadingModule.class,
tobiasheine/Movies
app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // }
import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component;
package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, TestStreamConverterModule.class, TestStreamApiModule.class, TestThreadingModule.class, },
// Path: app/src/androidTest/java/com/tobi/movies/TestApplicationComponent.java // @ApplicationScope // @Component(modules = FakeBackendModule.class) // public interface TestApplicationComponent extends ApplicationComponent{ // Backend backend(); // } // // Path: app/src/main/java/com/tobi/movies/misc/ImageModule.java // @Module // public class ImageModule { // // @Provides // ImageLoader provideImageLoader() { // return new ImageLoader(); // } // } // // Path: app/src/androidTest/java/com/tobi/movies/misc/TestThreadingModule.java // @Module // public class TestThreadingModule { // // @Provides // @IntoMap // @ThreadingKey(Threading.SUBSCRIBER) // Scheduler provideSubscriberScheduler() { // return Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR); // } // // @Provides // @IntoMap // @ThreadingKey(Threading.OBSERVER) // Scheduler provideObserverScheduler() { // return AndroidSchedulers.mainThread(); // } // // } // Path: app/src/androidTest/java/com/tobi/movies/popularstream/TestPopularMoviesComponent.java import com.tobi.movies.TestApplicationComponent; import com.tobi.movies.backend.Backend; import com.tobi.movies.di.ActivityScope; import com.tobi.movies.misc.ImageModule; import com.tobi.movies.misc.TestThreadingModule; import dagger.Component; package com.tobi.movies.popularstream; @ActivityScope @Component( modules = { ImageModule.class, TestStreamConverterModule.class, TestStreamApiModule.class, TestThreadingModule.class, },
dependencies = TestApplicationComponent.class
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsUseCase.java
// Path: app/src/main/java/com/tobi/movies/misc/AbstractObserver.java // public abstract class AbstractObserver<T> implements Observer<T> { // @Override // public void onCompleted() { // //no-op // } // // @Override // public void onError(Throwable e) { // //no-op // } // // @Override // public void onNext(T t) { // //no-op // } // }
import android.support.annotation.Nullable; import com.tobi.movies.misc.AbstractObserver; import rx.Scheduler; import rx.Subscription;
private Listener listener = NO_OP_LISTENER; public MovieDetailsUseCase( MovieDetailsRepository repository, Scheduler schedulerThread, Scheduler observerThread) { this.repository = repository; this.schedulerThread = schedulerThread; this.observerThread = observerThread; } @Nullable private MovieDetails movieDetails; @Override @Nullable public MovieDetails getMovieDetails() { return movieDetails; } @Override public void loadMovieDetails(long movieId) { if (subscription != null) { subscription.unsubscribe(); } subscription = repository .getMovieDetails(movieId) .subscribeOn(schedulerThread) .observeOn(observerThread)
// Path: app/src/main/java/com/tobi/movies/misc/AbstractObserver.java // public abstract class AbstractObserver<T> implements Observer<T> { // @Override // public void onCompleted() { // //no-op // } // // @Override // public void onError(Throwable e) { // //no-op // } // // @Override // public void onNext(T t) { // //no-op // } // } // Path: app/src/main/java/com/tobi/movies/posterdetails/MovieDetailsUseCase.java import android.support.annotation.Nullable; import com.tobi.movies.misc.AbstractObserver; import rx.Scheduler; import rx.Subscription; private Listener listener = NO_OP_LISTENER; public MovieDetailsUseCase( MovieDetailsRepository repository, Scheduler schedulerThread, Scheduler observerThread) { this.repository = repository; this.schedulerThread = schedulerThread; this.observerThread = observerThread; } @Nullable private MovieDetails movieDetails; @Override @Nullable public MovieDetails getMovieDetails() { return movieDetails; } @Override public void loadMovieDetails(long movieId) { if (subscription != null) { subscription.unsubscribe(); } subscription = repository .getMovieDetails(movieId) .subscribeOn(schedulerThread) .observeOn(observerThread)
.subscribe(new AbstractObserver<MovieDetails>() {
tobiasheine/Movies
app/src/main/java/com/tobi/movies/posterdetails/DetailsConverterModule.java
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // }
import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides;
package com.tobi.movies.posterdetails; @Module class DetailsConverterModule { @Provides
// Path: base/src/main/java/com/tobi/movies/Converter.java // public interface Converter<T, R> { // // R convert(T input); // } // Path: app/src/main/java/com/tobi/movies/posterdetails/DetailsConverterModule.java import com.tobi.movies.Converter; import dagger.Module; import dagger.Provides; package com.tobi.movies.posterdetails; @Module class DetailsConverterModule { @Provides
Converter<ApiMovieDetails, MovieDetails> provideDetailsConverter() {
xm0625/VBrowser-Android
app/src/main/java/com/xm/vbrowser/app/util/VideoFormatUtil.java
// Path: app/src/main/java/com/xm/vbrowser/app/entity/VideoFormat.java // public class VideoFormat { // private String name; // private List<String> mimeList; // // public VideoFormat(String name, List<String> mimeList) { // this.name = name; // this.mimeList = mimeList; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<String> getMimeList() { // return mimeList; // } // // public void setMimeList(List<String> mimeList) { // this.mimeList = mimeList; // } // } // // Path: app/src/main/java/com/xm/vbrowser/app/event/NewVideoItemDetectedEvent.java // public class NewVideoItemDetectedEvent{ // }
import android.text.TextUtils; import android.util.Log; import com.alibaba.fastjson.JSON; import com.xm.vbrowser.app.entity.VideoFormat; import com.xm.vbrowser.app.event.NewVideoItemDetectedEvent; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map;
package com.xm.vbrowser.app.util; /** * Created by xm on 17-8-16. */ public class VideoFormatUtil { private static final List<String> videoExtensionList = Arrays.asList( "m3u8", "mp4", "flv", "mpeg" );
// Path: app/src/main/java/com/xm/vbrowser/app/entity/VideoFormat.java // public class VideoFormat { // private String name; // private List<String> mimeList; // // public VideoFormat(String name, List<String> mimeList) { // this.name = name; // this.mimeList = mimeList; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<String> getMimeList() { // return mimeList; // } // // public void setMimeList(List<String> mimeList) { // this.mimeList = mimeList; // } // } // // Path: app/src/main/java/com/xm/vbrowser/app/event/NewVideoItemDetectedEvent.java // public class NewVideoItemDetectedEvent{ // } // Path: app/src/main/java/com/xm/vbrowser/app/util/VideoFormatUtil.java import android.text.TextUtils; import android.util.Log; import com.alibaba.fastjson.JSON; import com.xm.vbrowser.app.entity.VideoFormat; import com.xm.vbrowser.app.event.NewVideoItemDetectedEvent; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; package com.xm.vbrowser.app.util; /** * Created by xm on 17-8-16. */ public class VideoFormatUtil { private static final List<String> videoExtensionList = Arrays.asList( "m3u8", "mp4", "flv", "mpeg" );
private static final List<VideoFormat> videoFormatList = Arrays.asList(
xm0625/VBrowser-Android
app/src/main/java/fi/iki/elonen/NanoHTTPD.java
// Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public interface IStatus { // // String getDescription(); // // int getRequestStatus(); // } // // Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public enum Status implements IStatus { // SWITCH_PROTOCOL(101, "Switching Protocols"), // // OK(200, "OK"), // CREATED(201, "Created"), // ACCEPTED(202, "Accepted"), // NO_CONTENT(204, "No Content"), // PARTIAL_CONTENT(206, "Partial Content"), // MULTI_STATUS(207, "Multi-Status"), // // REDIRECT(301, "Moved Permanently"), // /** // * Many user agents mishandle 302 in ways that violate the RFC1945 // * spec (i.e., redirect a POST to a GET). 303 and 307 were added in // * RFC2616 to address this. You should prefer 303 and 307 unless the // * calling user agent does not support 303 and 307 functionality // */ // @Deprecated // FOUND(302, "Found"), // REDIRECT_SEE_OTHER(303, "See Other"), // NOT_MODIFIED(304, "Not Modified"), // TEMPORARY_REDIRECT(307, "Temporary Redirect"), // // BAD_REQUEST(400, "Bad Request"), // UNAUTHORIZED(401, "Unauthorized"), // FORBIDDEN(403, "Forbidden"), // NOT_FOUND(404, "Not Found"), // METHOD_NOT_ALLOWED(405, "Method Not Allowed"), // NOT_ACCEPTABLE(406, "Not Acceptable"), // REQUEST_TIMEOUT(408, "Request Timeout"), // CONFLICT(409, "Conflict"), // GONE(410, "Gone"), // LENGTH_REQUIRED(411, "Length Required"), // PRECONDITION_FAILED(412, "Precondition Failed"), // PAYLOAD_TOO_LARGE(413, "Payload Too Large"), // UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), // RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), // EXPECTATION_FAILED(417, "Expectation Failed"), // TOO_MANY_REQUESTS(429, "Too Many Requests"), // // INTERNAL_ERROR(500, "Internal Server Error"), // NOT_IMPLEMENTED(501, "Not Implemented"), // SERVICE_UNAVAILABLE(503, "Service Unavailable"), // UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported"); // // private final int requestStatus; // // private final String description; // // Status(int requestStatus, String description) { // this.requestStatus = requestStatus; // this.description = description; // } // // public static Status lookup(int requestStatus) { // for (Status status : Status.values()) { // if (status.getRequestStatus() == requestStatus) { // return status; // } // } // return null; // } // // @Override // public String getDescription() { // return "" + this.requestStatus + " " + this.description; // } // // @Override // public int getRequestStatus() { // return this.requestStatus; // } // // }
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.security.KeyStore; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.TrustManagerFactory; import fi.iki.elonen.NanoHTTPD.Response.IStatus; import fi.iki.elonen.NanoHTTPD.Response.Status;
OPTIONS, TRACE, CONNECT, PATCH, PROPFIND, PROPPATCH, MKCOL, MOVE, COPY, LOCK, UNLOCK; static Method lookup(String method) { if (method == null) return null; try { return valueOf(method); } catch (IllegalArgumentException e) { // TODO: Log it? return null; } } } /** * HTTP response. Return one of these from serve(). */ public static class Response implements Closeable {
// Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public interface IStatus { // // String getDescription(); // // int getRequestStatus(); // } // // Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public enum Status implements IStatus { // SWITCH_PROTOCOL(101, "Switching Protocols"), // // OK(200, "OK"), // CREATED(201, "Created"), // ACCEPTED(202, "Accepted"), // NO_CONTENT(204, "No Content"), // PARTIAL_CONTENT(206, "Partial Content"), // MULTI_STATUS(207, "Multi-Status"), // // REDIRECT(301, "Moved Permanently"), // /** // * Many user agents mishandle 302 in ways that violate the RFC1945 // * spec (i.e., redirect a POST to a GET). 303 and 307 were added in // * RFC2616 to address this. You should prefer 303 and 307 unless the // * calling user agent does not support 303 and 307 functionality // */ // @Deprecated // FOUND(302, "Found"), // REDIRECT_SEE_OTHER(303, "See Other"), // NOT_MODIFIED(304, "Not Modified"), // TEMPORARY_REDIRECT(307, "Temporary Redirect"), // // BAD_REQUEST(400, "Bad Request"), // UNAUTHORIZED(401, "Unauthorized"), // FORBIDDEN(403, "Forbidden"), // NOT_FOUND(404, "Not Found"), // METHOD_NOT_ALLOWED(405, "Method Not Allowed"), // NOT_ACCEPTABLE(406, "Not Acceptable"), // REQUEST_TIMEOUT(408, "Request Timeout"), // CONFLICT(409, "Conflict"), // GONE(410, "Gone"), // LENGTH_REQUIRED(411, "Length Required"), // PRECONDITION_FAILED(412, "Precondition Failed"), // PAYLOAD_TOO_LARGE(413, "Payload Too Large"), // UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), // RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), // EXPECTATION_FAILED(417, "Expectation Failed"), // TOO_MANY_REQUESTS(429, "Too Many Requests"), // // INTERNAL_ERROR(500, "Internal Server Error"), // NOT_IMPLEMENTED(501, "Not Implemented"), // SERVICE_UNAVAILABLE(503, "Service Unavailable"), // UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported"); // // private final int requestStatus; // // private final String description; // // Status(int requestStatus, String description) { // this.requestStatus = requestStatus; // this.description = description; // } // // public static Status lookup(int requestStatus) { // for (Status status : Status.values()) { // if (status.getRequestStatus() == requestStatus) { // return status; // } // } // return null; // } // // @Override // public String getDescription() { // return "" + this.requestStatus + " " + this.description; // } // // @Override // public int getRequestStatus() { // return this.requestStatus; // } // // } // Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.security.KeyStore; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.TrustManagerFactory; import fi.iki.elonen.NanoHTTPD.Response.IStatus; import fi.iki.elonen.NanoHTTPD.Response.Status; OPTIONS, TRACE, CONNECT, PATCH, PROPFIND, PROPPATCH, MKCOL, MOVE, COPY, LOCK, UNLOCK; static Method lookup(String method) { if (method == null) return null; try { return valueOf(method); } catch (IllegalArgumentException e) { // TODO: Log it? return null; } } } /** * HTTP response. Return one of these from serve(). */ public static class Response implements Closeable {
public interface IStatus {
xm0625/VBrowser-Android
app/src/main/java/fi/iki/elonen/SimpleWebServer.java
// Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public interface IStatus { // // String getDescription(); // // int getRequestStatus(); // }
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.StringTokenizer; import fi.iki.elonen.NanoHTTPD.Response.IStatus; import fi.iki.elonen.util.ServerRunner;
for (String directory : directories) { String dir = directory + "/"; msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></li>"); } msg.append("</section>"); } if (files.size() > 0) { msg.append("<section class=\"files\">"); for (String file : files) { msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>"); File curFile = new File(f, file); long len = curFile.length(); msg.append("&nbsp;<span class=\"filesize\">("); if (len < 1024) { msg.append(len).append(" bytes"); } else if (len < 1024 * 1024) { msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB"); } else { msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10000 % 100).append(" MB"); } msg.append(")</span></li>"); } msg.append("</section>"); } msg.append("</ul>"); } msg.append("</body></html>"); return msg.toString(); }
// Path: app/src/main/java/fi/iki/elonen/NanoHTTPD.java // public interface IStatus { // // String getDescription(); // // int getRequestStatus(); // } // Path: app/src/main/java/fi/iki/elonen/SimpleWebServer.java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.StringTokenizer; import fi.iki.elonen.NanoHTTPD.Response.IStatus; import fi.iki.elonen.util.ServerRunner; for (String directory : directories) { String dir = directory + "/"; msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></li>"); } msg.append("</section>"); } if (files.size() > 0) { msg.append("<section class=\"files\">"); for (String file : files) { msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>"); File curFile = new File(f, file); long len = curFile.length(); msg.append("&nbsp;<span class=\"filesize\">("); if (len < 1024) { msg.append(len).append(" bytes"); } else if (len < 1024 * 1024) { msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB"); } else { msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10000 % 100).append(" MB"); } msg.append(")</span></li>"); } msg.append("</section>"); } msg.append("</ul>"); } msg.append("</body></html>"); return msg.toString(); }
public static Response newFixedLengthResponse(IStatus status, String mimeType, String message) {
two-guys-one-code/TGOCMessagesActivity
Example/TGOCFirebase/app/src/main/java/chat/tgoc/com/tgocfirebase/Message.java
// Path: TGOCMessages/tgocmessage/src/main/java/br/com/tgoc/tgocmessage/TGOCMessageInterface.java // public interface TGOCMessageInterface { // String getSenderId(); // String getSenderDisplayName(); // Date getDate(); // String getText(); // boolean isMediaMessage(); // TGOCMessageMediaInterface getMedia(); // } // // Path: TGOCMessages/tgocmessage/src/main/java/br/com/tgoc/tgocmessage/TGOCMessageMediaInterface.java // public interface TGOCMessageMediaInterface { // View getView(Context context); // <T> T getData(); // }
import java.util.Date; import br.com.tgoc.tgocmessage.TGOCMessageInterface; import br.com.tgoc.tgocmessage.TGOCMessageMediaInterface;
package chat.tgoc.com.tgocfirebase; /** * Created by rodrigocavalcante on 9/12/16. */ public class Message implements TGOCMessageInterface { String senderId; String text; public String getSenderId() { return senderId; } @Override public String getSenderDisplayName() { return null; } @Override public Date getDate() { return null; } public void setSenderId(String senderId) { this.senderId = senderId; } public String getText() { return text; } @Override public boolean isMediaMessage() { return false; } @Override
// Path: TGOCMessages/tgocmessage/src/main/java/br/com/tgoc/tgocmessage/TGOCMessageInterface.java // public interface TGOCMessageInterface { // String getSenderId(); // String getSenderDisplayName(); // Date getDate(); // String getText(); // boolean isMediaMessage(); // TGOCMessageMediaInterface getMedia(); // } // // Path: TGOCMessages/tgocmessage/src/main/java/br/com/tgoc/tgocmessage/TGOCMessageMediaInterface.java // public interface TGOCMessageMediaInterface { // View getView(Context context); // <T> T getData(); // } // Path: Example/TGOCFirebase/app/src/main/java/chat/tgoc/com/tgocfirebase/Message.java import java.util.Date; import br.com.tgoc.tgocmessage.TGOCMessageInterface; import br.com.tgoc.tgocmessage.TGOCMessageMediaInterface; package chat.tgoc.com.tgocfirebase; /** * Created by rodrigocavalcante on 9/12/16. */ public class Message implements TGOCMessageInterface { String senderId; String text; public String getSenderId() { return senderId; } @Override public String getSenderDisplayName() { return null; } @Override public Date getDate() { return null; } public void setSenderId(String senderId) { this.senderId = senderId; } public String getText() { return text; } @Override public boolean isMediaMessage() { return false; } @Override
public TGOCMessageMediaInterface getMedia() {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/Restart.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Restart extends ServletAction { @Override
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/Restart.java import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Restart extends ServletAction { @Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/Restart.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Restart extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/Restart.java import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Restart extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/ImageUploadServlet.java
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class ImageUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699668L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // } // Path: src/main/java/com/sketchy/server/ImageUploadServlet.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class ImageUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699668L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/ImageUploadServlet.java
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class ImageUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699668L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try{ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart){ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); for (FileItem fileItem:files){ String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)){ // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")){ uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)){ throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // } // Path: src/main/java/com/sketchy/server/ImageUploadServlet.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class ImageUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699668L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try{ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart){ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); for (FileItem fileItem:files){ String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)){ // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")){ uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)){ throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file
SourceImageAttributes sourceImageAttributes = new SourceImageAttributes();
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/ImageUploadServlet.java
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils;
if (StringUtils.isNotBlank(uploadFileName)){ // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")){ uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)){ throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file SourceImageAttributes sourceImageAttributes = new SourceImageAttributes(); sourceImageAttributes.setImageName(uploadFileName); File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename()); if (pngFile.exists()) { throw new Exception("Can not Upload file. File '" + uploadFileName +"' already exists!"); } File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename()); // Convert the image to a .PNG file
// Path: src/main/java/com/sketchy/image/SourceImageAttributes.java // public class SourceImageAttributes extends ImageAttributes{ // // same as the Image Attributes (for now) // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/ImageUtils.java // public class ImageUtils{ // // public static BufferedImage loadImage(InputStream inputStream) throws Exception { // BufferedImage image = ImageIO.read(inputStream); // return image; // } // // public static BufferedImage loadImage(File imageFile) throws Exception { // BufferedImage image = ImageIO.read(imageFile); // return image; // } // // public static void saveImage(File imageFile, BufferedImage image) throws Exception { // ImageIO.write(image, "png", imageFile); // } // // } // Path: src/main/java/com/sketchy/server/ImageUploadServlet.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.image.SourceImageAttributes; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.ImageUtils; if (StringUtils.isNotBlank(uploadFileName)){ // Don't allow \\ in the filename, assume it's a directory separator and convert to "/" // and take the filename after the last "/" // This will fix the issue of Jetty not reading and serving files // with "\" (%5C) characters // This also fixes the issue of IE sometimes sending the whole path // (depending on the security settings) uploadFileName = StringUtils.replaceChars(uploadFileName, "\\", "/"); if (StringUtils.contains(uploadFileName, "/")){ uploadFileName = StringUtils.substringAfterLast(uploadFileName, "/"); } File uploadFile = HttpServer.getUploadFile(uploadFileName); // make sure filename is actually in the upload directory // we don't want any funny games if (!uploadFile.getParentFile().equals(HttpServer.IMAGE_UPLOAD_DIRECTORY)){ throw new RuntimeException("Can not upload File. Invalid directory!"); } // if saved ok, then need to add the data file SourceImageAttributes sourceImageAttributes = new SourceImageAttributes(); sourceImageAttributes.setImageName(uploadFileName); File pngFile = HttpServer.getUploadFile(sourceImageAttributes.getImageFilename()); if (pngFile.exists()) { throw new Exception("Can not Upload file. File '" + uploadFileName +"' already exists!"); } File dataFile = HttpServer.getUploadFile(sourceImageAttributes.getDataFilename()); // Convert the image to a .PNG file
BufferedImage image=ImageUtils.loadImage(fileItem.getInputStream());
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/pathing/impl/DotMatrixPathingProcessorProperties.java
// Path: src/main/java/com/sketchy/metadata/MetaData.java // public class MetaData { // // private List<MetaDataGroup> metaDataGroups = new ArrayList<MetaDataGroup>(); // private String helpUrl=null; // // public List<MetaDataGroup> getMetaDataGroups() { // return metaDataGroups; // } // // public void add(MetaDataGroup metaDataGroup){ // metaDataGroups.add(metaDataGroup); // } // // public String getHelpUrl() { // return helpUrl; // } // // public void setHelpUrl(String helpUrl) { // this.helpUrl = helpUrl; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessor.java // public abstract class PathingProcessor { // // public enum Status{ // INIT, DRAWING, PAUSED, CANCELLED, COMPLETED, ERROR; // } // // //protected PathingControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected PathingProcessor(PathingProcessorProperties properties){} // // private static PathingProcessor _this = null; // // public abstract PathingProcessorProperties getProperties(); // // public abstract void run(SketchyImage sketchyImage); // public abstract Status getStatus(); // public abstract String getStatusMessage(); // public abstract int getProgress(); // public abstract void cancelDrawing(); // public abstract void pauseDrawing(); // public abstract void resumeDrawing(); // // public synchronized static PathingProcessor getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(PathingControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static PathingProcessor newInstance(PathingProcessorProperties properties) throws Exception { // Class<? extends PathingProcessor> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this=null; // } // // Constructor<? extends PathingProcessor> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // // @SuppressWarnings("unchecked") // public static Map<String, String> getPathingProcessorClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.pathing.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<PathingProcessorProperties> hardwareControllerClass = (Class<PathingProcessorProperties>) clazz; // Class<PathingProcessor> implementationClass = (Class<PathingProcessor>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessorProperties.java // public abstract class PathingProcessorProperties extends MetaDataObject { // // private static final long serialVersionUID = 1188402725372240006L; // // public abstract Class<? extends PathingProcessor> getImplementationClass(); // // }
import com.sketchy.pathing.PathingProcessor; import com.sketchy.pathing.PathingProcessorProperties; import com.sketchy.metadata.MetaData;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.pathing.impl; public class DotMatrixPathingProcessorProperties extends PathingProcessorProperties { private static final long serialVersionUID = -2722385158493064636L; @Override
// Path: src/main/java/com/sketchy/metadata/MetaData.java // public class MetaData { // // private List<MetaDataGroup> metaDataGroups = new ArrayList<MetaDataGroup>(); // private String helpUrl=null; // // public List<MetaDataGroup> getMetaDataGroups() { // return metaDataGroups; // } // // public void add(MetaDataGroup metaDataGroup){ // metaDataGroups.add(metaDataGroup); // } // // public String getHelpUrl() { // return helpUrl; // } // // public void setHelpUrl(String helpUrl) { // this.helpUrl = helpUrl; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessor.java // public abstract class PathingProcessor { // // public enum Status{ // INIT, DRAWING, PAUSED, CANCELLED, COMPLETED, ERROR; // } // // //protected PathingControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected PathingProcessor(PathingProcessorProperties properties){} // // private static PathingProcessor _this = null; // // public abstract PathingProcessorProperties getProperties(); // // public abstract void run(SketchyImage sketchyImage); // public abstract Status getStatus(); // public abstract String getStatusMessage(); // public abstract int getProgress(); // public abstract void cancelDrawing(); // public abstract void pauseDrawing(); // public abstract void resumeDrawing(); // // public synchronized static PathingProcessor getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(PathingControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static PathingProcessor newInstance(PathingProcessorProperties properties) throws Exception { // Class<? extends PathingProcessor> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this=null; // } // // Constructor<? extends PathingProcessor> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // // @SuppressWarnings("unchecked") // public static Map<String, String> getPathingProcessorClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.pathing.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<PathingProcessorProperties> hardwareControllerClass = (Class<PathingProcessorProperties>) clazz; // Class<PathingProcessor> implementationClass = (Class<PathingProcessor>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessorProperties.java // public abstract class PathingProcessorProperties extends MetaDataObject { // // private static final long serialVersionUID = 1188402725372240006L; // // public abstract Class<? extends PathingProcessor> getImplementationClass(); // // } // Path: src/main/java/com/sketchy/pathing/impl/DotMatrixPathingProcessorProperties.java import com.sketchy.pathing.PathingProcessor; import com.sketchy.pathing.PathingProcessorProperties; import com.sketchy.metadata.MetaData; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.pathing.impl; public class DotMatrixPathingProcessorProperties extends PathingProcessorProperties { private static final long serialVersionUID = -2722385158493064636L; @Override
public Class<? extends PathingProcessor> getImplementationClass() {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/pathing/impl/DotMatrixPathingProcessorProperties.java
// Path: src/main/java/com/sketchy/metadata/MetaData.java // public class MetaData { // // private List<MetaDataGroup> metaDataGroups = new ArrayList<MetaDataGroup>(); // private String helpUrl=null; // // public List<MetaDataGroup> getMetaDataGroups() { // return metaDataGroups; // } // // public void add(MetaDataGroup metaDataGroup){ // metaDataGroups.add(metaDataGroup); // } // // public String getHelpUrl() { // return helpUrl; // } // // public void setHelpUrl(String helpUrl) { // this.helpUrl = helpUrl; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessor.java // public abstract class PathingProcessor { // // public enum Status{ // INIT, DRAWING, PAUSED, CANCELLED, COMPLETED, ERROR; // } // // //protected PathingControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected PathingProcessor(PathingProcessorProperties properties){} // // private static PathingProcessor _this = null; // // public abstract PathingProcessorProperties getProperties(); // // public abstract void run(SketchyImage sketchyImage); // public abstract Status getStatus(); // public abstract String getStatusMessage(); // public abstract int getProgress(); // public abstract void cancelDrawing(); // public abstract void pauseDrawing(); // public abstract void resumeDrawing(); // // public synchronized static PathingProcessor getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(PathingControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static PathingProcessor newInstance(PathingProcessorProperties properties) throws Exception { // Class<? extends PathingProcessor> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this=null; // } // // Constructor<? extends PathingProcessor> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // // @SuppressWarnings("unchecked") // public static Map<String, String> getPathingProcessorClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.pathing.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<PathingProcessorProperties> hardwareControllerClass = (Class<PathingProcessorProperties>) clazz; // Class<PathingProcessor> implementationClass = (Class<PathingProcessor>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessorProperties.java // public abstract class PathingProcessorProperties extends MetaDataObject { // // private static final long serialVersionUID = 1188402725372240006L; // // public abstract Class<? extends PathingProcessor> getImplementationClass(); // // }
import com.sketchy.pathing.PathingProcessor; import com.sketchy.pathing.PathingProcessorProperties; import com.sketchy.metadata.MetaData;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.pathing.impl; public class DotMatrixPathingProcessorProperties extends PathingProcessorProperties { private static final long serialVersionUID = -2722385158493064636L; @Override public Class<? extends PathingProcessor> getImplementationClass() { return DotMatrixPathingProcessor.class; } @Override
// Path: src/main/java/com/sketchy/metadata/MetaData.java // public class MetaData { // // private List<MetaDataGroup> metaDataGroups = new ArrayList<MetaDataGroup>(); // private String helpUrl=null; // // public List<MetaDataGroup> getMetaDataGroups() { // return metaDataGroups; // } // // public void add(MetaDataGroup metaDataGroup){ // metaDataGroups.add(metaDataGroup); // } // // public String getHelpUrl() { // return helpUrl; // } // // public void setHelpUrl(String helpUrl) { // this.helpUrl = helpUrl; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessor.java // public abstract class PathingProcessor { // // public enum Status{ // INIT, DRAWING, PAUSED, CANCELLED, COMPLETED, ERROR; // } // // //protected PathingControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected PathingProcessor(PathingProcessorProperties properties){} // // private static PathingProcessor _this = null; // // public abstract PathingProcessorProperties getProperties(); // // public abstract void run(SketchyImage sketchyImage); // public abstract Status getStatus(); // public abstract String getStatusMessage(); // public abstract int getProgress(); // public abstract void cancelDrawing(); // public abstract void pauseDrawing(); // public abstract void resumeDrawing(); // // public synchronized static PathingProcessor getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(PathingControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static PathingProcessor newInstance(PathingProcessorProperties properties) throws Exception { // Class<? extends PathingProcessor> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this=null; // } // // Constructor<? extends PathingProcessor> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting PathingController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // // @SuppressWarnings("unchecked") // public static Map<String, String> getPathingProcessorClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.pathing.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<PathingProcessorProperties> hardwareControllerClass = (Class<PathingProcessorProperties>) clazz; // Class<PathingProcessor> implementationClass = (Class<PathingProcessor>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // } // // Path: src/main/java/com/sketchy/pathing/PathingProcessorProperties.java // public abstract class PathingProcessorProperties extends MetaDataObject { // // private static final long serialVersionUID = 1188402725372240006L; // // public abstract Class<? extends PathingProcessor> getImplementationClass(); // // } // Path: src/main/java/com/sketchy/pathing/impl/DotMatrixPathingProcessorProperties.java import com.sketchy.pathing.PathingProcessor; import com.sketchy.pathing.PathingProcessorProperties; import com.sketchy.metadata.MetaData; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.pathing.impl; public class DotMatrixPathingProcessorProperties extends PathingProcessorProperties { private static final long serialVersionUID = -2722385158493064636L; @Override public Class<? extends PathingProcessor> getImplementationClass() { return DotMatrixPathingProcessor.class; } @Override
public MetaData getMetaData() {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/UpgradeUploadServlet.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.File; import java.io.IOException; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class UpgradeUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699663L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/UpgradeUploadServlet.java import java.io.File; import java.io.IOException; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class UpgradeUploadServlet extends HttpServlet { private static final int MAX_SIZE = 10000000; // 10Mbytes private static final long serialVersionUID = -6172468221875699663L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/UpgradeSoftware.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.File; import javax.servlet.http.HttpServletRequest; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class UpgradeSoftware extends ServletAction { @Override
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/UpgradeSoftware.java import java.io.File; import javax.servlet.http.HttpServletRequest; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class UpgradeSoftware extends ServletAction { @Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/UpgradeSoftware.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.File; import javax.servlet.http.HttpServletRequest; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class UpgradeSoftware extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/UpgradeSoftware.java import java.io.File; import javax.servlet.http.HttpServletRequest; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class UpgradeSoftware extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/Shutdown.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Shutdown extends ServletAction { @Override
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/Shutdown.java import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Shutdown extends ServletAction { @Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/Shutdown.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Shutdown extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/Shutdown.java import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import javax.servlet.http.HttpServletRequest; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class Shutdown extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/utils/JSONUtils.java
// Path: src/main/java/com/sketchy/metadata/BooleanStringFactory.java // public class BooleanStringFactory implements ObjectFactory { // @SuppressWarnings("rawtypes") // @Override // public Object instantiate(ObjectBinder arg0, Object arg1, Type arg2, Class arg3) { // if (arg1 instanceof String){ // return new Boolean((String) arg1); // } else if (arg1 instanceof Boolean){ // return (Boolean) arg1; // } else { // return false; // } // } // } // // Path: src/main/java/com/sketchy/metadata/BooleanStringTransformer.java // public class BooleanStringTransformer extends AbstractTransformer { // // @Override // public void transform(Object arg0) { // if (arg0 instanceof Boolean){ // getContext().writeQuoted(((boolean) arg0)?"true":"false"); // } else { // getContext().writeQuoted(""); // } // } // // // }
import flexjson.JSONDeserializer; import flexjson.JSONSerializer; import com.sketchy.metadata.BooleanStringFactory; import com.sketchy.metadata.BooleanStringTransformer;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.utils; public class JSONUtils { public static Object fromJson(String json){ JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>();
// Path: src/main/java/com/sketchy/metadata/BooleanStringFactory.java // public class BooleanStringFactory implements ObjectFactory { // @SuppressWarnings("rawtypes") // @Override // public Object instantiate(ObjectBinder arg0, Object arg1, Type arg2, Class arg3) { // if (arg1 instanceof String){ // return new Boolean((String) arg1); // } else if (arg1 instanceof Boolean){ // return (Boolean) arg1; // } else { // return false; // } // } // } // // Path: src/main/java/com/sketchy/metadata/BooleanStringTransformer.java // public class BooleanStringTransformer extends AbstractTransformer { // // @Override // public void transform(Object arg0) { // if (arg0 instanceof Boolean){ // getContext().writeQuoted(((boolean) arg0)?"true":"false"); // } else { // getContext().writeQuoted(""); // } // } // // // } // Path: src/main/java/com/sketchy/utils/JSONUtils.java import flexjson.JSONDeserializer; import flexjson.JSONSerializer; import com.sketchy.metadata.BooleanStringFactory; import com.sketchy.metadata.BooleanStringTransformer; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.utils; public class JSONUtils { public static Object fromJson(String json){ JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>();
deserializer = deserializer.use(Boolean.class, new BooleanStringFactory());
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/utils/JSONUtils.java
// Path: src/main/java/com/sketchy/metadata/BooleanStringFactory.java // public class BooleanStringFactory implements ObjectFactory { // @SuppressWarnings("rawtypes") // @Override // public Object instantiate(ObjectBinder arg0, Object arg1, Type arg2, Class arg3) { // if (arg1 instanceof String){ // return new Boolean((String) arg1); // } else if (arg1 instanceof Boolean){ // return (Boolean) arg1; // } else { // return false; // } // } // } // // Path: src/main/java/com/sketchy/metadata/BooleanStringTransformer.java // public class BooleanStringTransformer extends AbstractTransformer { // // @Override // public void transform(Object arg0) { // if (arg0 instanceof Boolean){ // getContext().writeQuoted(((boolean) arg0)?"true":"false"); // } else { // getContext().writeQuoted(""); // } // } // // // }
import flexjson.JSONDeserializer; import flexjson.JSONSerializer; import com.sketchy.metadata.BooleanStringFactory; import com.sketchy.metadata.BooleanStringTransformer;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.utils; public class JSONUtils { public static Object fromJson(String json){ JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); return deserializer.deserialize(json); } public static String toJson(Object object){ JSONSerializer serializer = new JSONSerializer();
// Path: src/main/java/com/sketchy/metadata/BooleanStringFactory.java // public class BooleanStringFactory implements ObjectFactory { // @SuppressWarnings("rawtypes") // @Override // public Object instantiate(ObjectBinder arg0, Object arg1, Type arg2, Class arg3) { // if (arg1 instanceof String){ // return new Boolean((String) arg1); // } else if (arg1 instanceof Boolean){ // return (Boolean) arg1; // } else { // return false; // } // } // } // // Path: src/main/java/com/sketchy/metadata/BooleanStringTransformer.java // public class BooleanStringTransformer extends AbstractTransformer { // // @Override // public void transform(Object arg0) { // if (arg0 instanceof Boolean){ // getContext().writeQuoted(((boolean) arg0)?"true":"false"); // } else { // getContext().writeQuoted(""); // } // } // // // } // Path: src/main/java/com/sketchy/utils/JSONUtils.java import flexjson.JSONDeserializer; import flexjson.JSONSerializer; import com.sketchy.metadata.BooleanStringFactory; import com.sketchy.metadata.BooleanStringTransformer; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.utils; public class JSONUtils { public static Object fromJson(String json){ JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); return deserializer.deserialize(json); } public static String toJson(Object object){ JSONSerializer serializer = new JSONSerializer();
serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/JSONServletResult.java
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import java.util.Map; import com.sketchy.utils.JSONUtils; import java.util.LinkedHashMap;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class JSONServletResult { private static final String KEY_STATUS="status"; private static final String KEY_MESSAGE="message"; public enum Status{ SUCCESS, ERROR; } private Map<String, Object> map = new LinkedHashMap<>(); public JSONServletResult(Status status){ map.put(KEY_STATUS, status); setMessage(""); } public JSONServletResult(Status status, String message){ map.put(KEY_STATUS, status); setMessage(message); } public void setMessage(String message){ map.put(KEY_MESSAGE, message); } public void put(String key, Object value){ if (key.equals(KEY_STATUS)){ throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); } if (key.equals(KEY_MESSAGE)){ throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); } map.put(key, value); } public String toJSONString() {
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/server/JSONServletResult.java import java.util.Map; import com.sketchy.utils.JSONUtils; import java.util.LinkedHashMap; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class JSONServletResult { private static final String KEY_STATUS="status"; private static final String KEY_MESSAGE="message"; public enum Status{ SUCCESS, ERROR; } private Map<String, Object> map = new LinkedHashMap<>(); public JSONServletResult(Status status){ map.put(KEY_STATUS, status); setMessage(""); } public JSONServletResult(Status status, String message){ map.put(KEY_STATUS, status); setMessage(message); } public void setMessage(String message){ map.put(KEY_MESSAGE, message); } public void put(String key, Object value){ if (key.equals(KEY_STATUS)){ throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); } if (key.equals(KEY_MESSAGE)){ throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); } map.put(key, value); } public String toJSONString() {
return JSONUtils.toJson(map);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/hardware/impl/RaspberryPIServoController.java
// Path: src/main/java/com/sketchy/hardware/Direction.java // public enum Direction { // BACKWARD(-1), NONE(0), FORWARD(1); // // private int value; // // private Direction(int value) { // this.value = value; // } // // public static Direction fromValue(int value){ // if (value==0) { // return NONE; // } else if (value>0){ // return FORWARD; // } else { // return BACKWARD; // } // } // // // public int getValue() { // return value; // } // // } // // Path: src/main/java/com/sketchy/hardware/HardwareController.java // public abstract class HardwareController { // // //protected HardwareControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected HardwareController(HardwareControllerProperties properties){} // // private static HardwareController _this = null; // // public abstract HardwareControllerProperties getProperties(); // // public synchronized static HardwareController getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(HardwareControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static HardwareController newInstance(HardwareControllerProperties properties) throws Exception { // Class<? extends HardwareController> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this.shutDown(); // _this=null; // } // // Constructor<? extends HardwareController> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting HardwareController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting HardwareController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // public abstract void penUp(); // // public abstract void penDown(); // // // Based on Bresenham's line algorithm // public void moveMotors(int leftSteps, int rightSteps, long delayInMicroSeconds) throws Exception { // // Just return if no steps occurring // if ((leftSteps==0) && (rightSteps==0)) return; // // boolean swapSteps=Math.abs(rightSteps) > Math.abs(leftSteps); // if (swapSteps){ // int temp=leftSteps; // leftSteps=rightSteps; // rightSteps=temp; // } // // Direction leftMotorDirection = Direction.fromValue(leftSteps); // Direction rightMotorDirection = Direction.fromValue(rightSteps); // // leftSteps = Math.abs(leftSteps); // rightSteps = Math.abs(rightSteps); // // int error=leftSteps/2; // for (int steps=0;steps<leftSteps;steps++){ // Direction stepRight=Direction.NONE; // error-=rightSteps; // if(error<0){ // stepRight=rightMotorDirection; // error+=leftSteps; // } // if (swapSteps){ // stepMotors(stepRight, leftMotorDirection, delayInMicroSeconds); // } else { // stepMotors(leftMotorDirection, stepRight, delayInMicroSeconds); // } // } // } // // public abstract void stepMotors(Direction leftMotorDirection, Direction rightMotorDirection, long delayInMicroSeconds); // // public abstract void enableMotors(); // // public abstract void disableMotors(); // // public abstract void shutDown(); // // @SuppressWarnings("unchecked") // public static Map<String, String> getHardwareControllerClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.hardware.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<HardwareControllerProperties> hardwareControllerClass = (Class<HardwareControllerProperties>) clazz; // Class<HardwareController> implementationClass = (Class<HardwareController>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // }
import java.io.File; import org.apache.commons.io.FileUtils; import com.pi4j.wiringpi.Gpio; import com.sketchy.hardware.Direction; import com.sketchy.hardware.HardwareController;
} public synchronized void penUp(){ if (properties.getPenUpPosition()!=lastPosition){ try{ int penUpValue=(int) ((SERVO_MAX_VALUE-SERVO_MIN_VALUE)/100.0*properties.getPenUpPosition()+SERVO_MIN_VALUE); String servoPenUpCommand = buildServoCommand(properties.getPenPinNumber(), penUpValue); FileUtils.writeStringToFile(servoPipeFile, servoPenUpCommand); } catch (Exception e){ throw new RuntimeException(e.getMessage()); } Gpio.delayMicroseconds(properties.getPenUpPeriodInMilliseconds()*1000); lastPosition=properties.getPenUpPosition(); } } public synchronized void penDown(){ if (properties.getPenDownPosition()!=lastPosition){ try{ int penDownValue=(int) ((SERVO_MAX_VALUE-SERVO_MIN_VALUE)/100.0*properties.getPenDownPosition()+SERVO_MIN_VALUE); String servoPenDownCommand = buildServoCommand(properties.getPenPinNumber(), penDownValue); FileUtils.writeStringToFile(servoPipeFile, servoPenDownCommand); } catch (Exception e){ throw new RuntimeException(e.getMessage()); } Gpio.delayMicroseconds(properties.getPenDownPeriodInMilliseconds()*1000); lastPosition=properties.getPenDownPosition(); } }
// Path: src/main/java/com/sketchy/hardware/Direction.java // public enum Direction { // BACKWARD(-1), NONE(0), FORWARD(1); // // private int value; // // private Direction(int value) { // this.value = value; // } // // public static Direction fromValue(int value){ // if (value==0) { // return NONE; // } else if (value>0){ // return FORWARD; // } else { // return BACKWARD; // } // } // // // public int getValue() { // return value; // } // // } // // Path: src/main/java/com/sketchy/hardware/HardwareController.java // public abstract class HardwareController { // // //protected HardwareControllerProperties properties = null; // // This is to ensure that the Constructor in subclasses is created // protected HardwareController(HardwareControllerProperties properties){} // // private static HardwareController _this = null; // // public abstract HardwareControllerProperties getProperties(); // // public synchronized static HardwareController getInstance() throws Exception { // if (_this==null){ // throw new Exception("Instance not created. Use newInstance(HardwareControllerProperties properties) first!"); // } // return _this; // } // // public synchronized static HardwareController newInstance(HardwareControllerProperties properties) throws Exception { // Class<? extends HardwareController> controllerClass = properties.getImplementationClass(); // // try{ // if (_this!=null){ // // existing instance // _this.shutDown(); // _this=null; // } // // Constructor<? extends HardwareController> constructor = controllerClass.getConstructor(new Class[]{properties.getClass()}); // _this=constructor.newInstance(new Object[]{properties}); // } catch (IllegalAccessException e){ // throw new Exception("Error Getting HardwareController Instance from Class '" + controllerClass.getName() + "'! " + e.toString()); // } catch (InstantiationException e){ // throw new Exception("Error Getting HardwareController Instance from Class '" + controllerClass.getName() + "'!" + e.toString()); // } catch (InvocationTargetException e){ // throw new Exception(e.getTargetException().getMessage()); // } // // return _this; // } // // public abstract void penUp(); // // public abstract void penDown(); // // // Based on Bresenham's line algorithm // public void moveMotors(int leftSteps, int rightSteps, long delayInMicroSeconds) throws Exception { // // Just return if no steps occurring // if ((leftSteps==0) && (rightSteps==0)) return; // // boolean swapSteps=Math.abs(rightSteps) > Math.abs(leftSteps); // if (swapSteps){ // int temp=leftSteps; // leftSteps=rightSteps; // rightSteps=temp; // } // // Direction leftMotorDirection = Direction.fromValue(leftSteps); // Direction rightMotorDirection = Direction.fromValue(rightSteps); // // leftSteps = Math.abs(leftSteps); // rightSteps = Math.abs(rightSteps); // // int error=leftSteps/2; // for (int steps=0;steps<leftSteps;steps++){ // Direction stepRight=Direction.NONE; // error-=rightSteps; // if(error<0){ // stepRight=rightMotorDirection; // error+=leftSteps; // } // if (swapSteps){ // stepMotors(stepRight, leftMotorDirection, delayInMicroSeconds); // } else { // stepMotors(leftMotorDirection, stepRight, delayInMicroSeconds); // } // } // } // // public abstract void stepMotors(Direction leftMotorDirection, Direction rightMotorDirection, long delayInMicroSeconds); // // public abstract void enableMotors(); // // public abstract void disableMotors(); // // public abstract void shutDown(); // // @SuppressWarnings("unchecked") // public static Map<String, String> getHardwareControllerClassMap() throws Exception { // List<Class<?>> classes = ClassScanner.getClassesForPackage("com.sketchy.hardware.impl", MetaDataObject.class); // Map<String, String> classMap = new LinkedHashMap<String, String>(); // for (Class<?> clazz:classes){ // Class<HardwareControllerProperties> hardwareControllerClass = (Class<HardwareControllerProperties>) clazz; // Class<HardwareController> implementationClass = (Class<HardwareController>) hardwareControllerClass.newInstance().getImplementationClass(); // classMap.put(implementationClass.getName(), clazz.getName()); // } // return classMap; // } // // } // Path: src/main/java/com/sketchy/hardware/impl/RaspberryPIServoController.java import java.io.File; import org.apache.commons.io.FileUtils; import com.pi4j.wiringpi.Gpio; import com.sketchy.hardware.Direction; import com.sketchy.hardware.HardwareController; } public synchronized void penUp(){ if (properties.getPenUpPosition()!=lastPosition){ try{ int penUpValue=(int) ((SERVO_MAX_VALUE-SERVO_MIN_VALUE)/100.0*properties.getPenUpPosition()+SERVO_MIN_VALUE); String servoPenUpCommand = buildServoCommand(properties.getPenPinNumber(), penUpValue); FileUtils.writeStringToFile(servoPipeFile, servoPenUpCommand); } catch (Exception e){ throw new RuntimeException(e.getMessage()); } Gpio.delayMicroseconds(properties.getPenUpPeriodInMilliseconds()*1000); lastPosition=properties.getPenUpPosition(); } } public synchronized void penDown(){ if (properties.getPenDownPosition()!=lastPosition){ try{ int penDownValue=(int) ((SERVO_MAX_VALUE-SERVO_MIN_VALUE)/100.0*properties.getPenDownPosition()+SERVO_MIN_VALUE); String servoPenDownCommand = buildServoCommand(properties.getPenPinNumber(), penDownValue); FileUtils.writeStringToFile(servoPipeFile, servoPenDownCommand); } catch (Exception e){ throw new RuntimeException(e.getMessage()); } Gpio.delayMicroseconds(properties.getPenDownPeriodInMilliseconds()*1000); lastPosition=properties.getPenDownPosition(); } }
public synchronized void stepMotors(Direction leftMotorDirection, Direction rightMotorDirection, long delayInMicroSeconds){
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/ManageNetworkSettings.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/server/action/ManageNetworkSettings.java import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/ManageNetworkSettings.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/server/action/ManageNetworkSettings.java import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/ManageNetworkSettings.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override public JSONServletResult execute(HttpServletRequest request) throws Exception { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try{ if ((!WPA_SUPPLICANT_FILE.isFile()) || (!WPA_SUPPLICANT_FILE.exists())){ throw new Exception("Can not update wpa_supplicant.conf file! File '" + WPA_SUPPLICANT_FILE.getPath() + "' not found."); } if (!WPA_SUPPLICANT_FILE.canWrite()){ throw new Exception("Can not update Network Settings! Can not write to File '" + WPA_SUPPLICANT_FILE.getPath() + "'."); } String responseBody = getResponseBody(request); if (!StringUtils.isBlank(responseBody)){
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // // Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/server/action/ManageNetworkSettings.java import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; import com.sketchy.utils.JSONUtils; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class ManageNetworkSettings extends ServletAction { private static File WPA_SUPPLICANT_FILE = new File("/etc/wpa_supplicant/wpa_supplicant.conf"); @SuppressWarnings("unchecked") @Override public JSONServletResult execute(HttpServletRequest request) throws Exception { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try{ if ((!WPA_SUPPLICANT_FILE.isFile()) || (!WPA_SUPPLICANT_FILE.exists())){ throw new Exception("Can not update wpa_supplicant.conf file! File '" + WPA_SUPPLICANT_FILE.getPath() + "' not found."); } if (!WPA_SUPPLICANT_FILE.canWrite()){ throw new Exception("Can not update Network Settings! Can not write to File '" + WPA_SUPPLICANT_FILE.getPath() + "'."); } String responseBody = getResponseBody(request); if (!StringUtils.isBlank(responseBody)){
Map<String, String> map = (Map<String, String>) JSONUtils.fromJson(responseBody);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/metadata/MetaDataObject.java
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import com.sketchy.utils.JSONUtils; import java.io.Serializable;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.metadata; public abstract class MetaDataObject implements Serializable{ private static final long serialVersionUID = -4735684498302103441L; public abstract MetaData getMetaData(); public static MetaDataObject fromJson(String json){
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/metadata/MetaDataObject.java import com.sketchy.utils.JSONUtils; import java.io.Serializable; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.metadata; public abstract class MetaDataObject implements Serializable{ private static final long serialVersionUID = -4735684498302103441L; public abstract MetaData getMetaData(); public static MetaDataObject fromJson(String json){
return (MetaDataObject) JSONUtils.fromJson(json);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/image/ImageAttributes.java
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // }
import com.sketchy.utils.JSONUtils;
public void setImageName(String imageName) { this.imageName = imageName; } public String getImageName() { return imageName; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getDataFilename() { return getDataFilename(imageName); } public String getImageFilename() { return getImageFilename(imageName); } public String toJson(){
// Path: src/main/java/com/sketchy/utils/JSONUtils.java // public class JSONUtils { // // public static Object fromJson(String json){ // JSONDeserializer<Object> deserializer = new JSONDeserializer<Object>(); // deserializer = deserializer.use(Boolean.class, new BooleanStringFactory()); // deserializer = deserializer.use(boolean.class, new BooleanStringFactory()); // return deserializer.deserialize(json); // } // // public static String toJson(Object object){ // JSONSerializer serializer = new JSONSerializer(); // serializer = serializer.transform(new BooleanStringTransformer(), Boolean.class); // serializer = serializer.transform(new BooleanStringTransformer(), boolean.class); // return serializer.deepSerialize(object); // } // // // } // Path: src/main/java/com/sketchy/image/ImageAttributes.java import com.sketchy.utils.JSONUtils; public void setImageName(String imageName) { this.imageName = imageName; } public String getImageName() { return imageName; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getDataFilename() { return getDataFilename(imageName); } public String getImageFilename() { return getImageFilename(imageName); } public String toJson(){
return JSONUtils.toJson(this);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/GetCurrentVersion.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.File; import java.io.FileInputStream; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class GetCurrentVersion extends ServletAction { @Override
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/GetCurrentVersion.java import java.io.File; import java.io.FileInputStream; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class GetCurrentVersion extends ServletAction { @Override
public JSONServletResult execute(HttpServletRequest request) throws Exception {
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/action/GetCurrentVersion.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.File; import java.io.FileInputStream; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class GetCurrentVersion extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public final class JSONServletResult { // // private static final String KEY_STATUS="status"; // private static final String KEY_MESSAGE="message"; // // public enum Status{ // SUCCESS, ERROR; // } // // private Map<String, Object> map = new LinkedHashMap<>(); // // public JSONServletResult(Status status){ // map.put(KEY_STATUS, status); // setMessage(""); // } // // public JSONServletResult(Status status, String message){ // map.put(KEY_STATUS, status); // setMessage(message); // } // // public void setMessage(String message){ // map.put(KEY_MESSAGE, message); // } // // public void put(String key, Object value){ // if (key.equals(KEY_STATUS)){ // throw new RuntimeException("Can not set value with key '" + KEY_STATUS + "'! Internal Use only!"); // } // if (key.equals(KEY_MESSAGE)){ // throw new RuntimeException("Can not set value with key '" + KEY_MESSAGE + "'! Internal Use only!"); // } // map.put(key, value); // } // // public String toJSONString() { // return JSONUtils.toJson(map); // } // // } // // Path: src/main/java/com/sketchy/server/ServletAction.java // public abstract class ServletAction { // // private static final Map<String, ServletAction> instanceMap = new HashMap<String, ServletAction>(); // // public static synchronized ServletAction getInstance(String servletActionClassName) throws Exception { // try{ // ServletAction servletAction = instanceMap.get(servletActionClassName); // if (servletAction==null){ // servletAction = (ServletAction) Class.forName(servletActionClassName).newInstance(); // // instanceMap.put(servletActionClassName, servletAction); // } // return servletAction; // } catch (ClassNotFoundException e){ // throw e; // } // catch (Exception e){ // throw new Exception("Error creating ServletAction Instance for class '" + servletActionClassName + "'! " + e.getMessage()); // } // } // // public abstract JSONServletResult execute(HttpServletRequest request) throws Exception; // // public static String getResponseBody(HttpServletRequest request) throws IOException { // return IOUtils.toString(request.getInputStream()); // } // // // } // // Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/action/GetCurrentVersion.java import java.io.File; import java.io.FileInputStream; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import com.sketchy.server.JSONServletResult; import com.sketchy.server.ServletAction; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server.action; public class GetCurrentVersion extends ServletAction { @Override public JSONServletResult execute(HttpServletRequest request) throws Exception {
JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS);
MHAVLOVICK/Sketchy
src/main/java/com/sketchy/server/JsonServlet.java
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult.Status;
/* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class JsonServlet extends HttpServlet { private static final String ACTION_PACKAGE = "com.sketchy.server.action."; private static final long serialVersionUID = 6826724318580539026L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/")) pathInfo = StringUtils.substringAfter(pathInfo, "/"); String action = ACTION_PACKAGE + pathInfo; JSONServletResult jsonServletResult = null; try{ ServletAction servletAction = ServletAction.getInstance(action); jsonServletResult = servletAction.execute(request); } catch (ClassNotFoundException e){
// Path: src/main/java/com/sketchy/server/JSONServletResult.java // public enum Status{ // SUCCESS, ERROR; // } // Path: src/main/java/com/sketchy/server/JsonServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.sketchy.server.JSONServletResult.Status; /* Sketchy Copyright (C) 2015 Matthew Havlovick http://www.quickdrawbot.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Contact Info: Matt Havlovick QuickDraw 470 I St Washougal, WA 98671 matt@quickdrawbot.com http://www.quickdrawbot.com This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package com.sketchy.server; public final class JsonServlet extends HttpServlet { private static final String ACTION_PACKAGE = "com.sketchy.server.action."; private static final long serialVersionUID = 6826724318580539026L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/")) pathInfo = StringUtils.substringAfter(pathInfo, "/"); String action = ACTION_PACKAGE + pathInfo; JSONServletResult jsonServletResult = null; try{ ServletAction servletAction = ServletAction.getInstance(action); jsonServletResult = servletAction.execute(request); } catch (ClassNotFoundException e){
jsonServletResult = new JSONServletResult(Status.ERROR, "ServletAction '" + pathInfo + "' not found! " + e.getMessage());
qiujuer/OkHttpPacker
okhttp/src/main/java/net/qiujuer/common/okhttp/core/RequestBuilder.java
// Path: okhttp/src/main/java/net/qiujuer/common/okhttp/io/IOParam.java // public class IOParam { // public String key; // public File file; // // public IOParam(String key, File file) { // this.key = key; // this.file = file; // } // } // // Path: okhttp/src/main/java/net/qiujuer/common/okhttp/io/StrParam.java // public class StrParam { // public String key; // public String value; // // public StrParam(String key, String value) { // this.key = key; // this.value = value; // } // // public StrParam(String key, int value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, float value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, long value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, double value) { // this(key, String.valueOf(value)); // } // }
import net.qiujuer.common.okhttp.io.IOParam; import net.qiujuer.common.okhttp.io.StrParam; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import okhttp3.Request; import okhttp3.RequestBody;
/* * Copyright (C) 2014-2016 Qiujuer <qiujuer@live.cn> * WebSite http://www.qiujuer.net * Author Qiujuer * * 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 net.qiujuer.common.okhttp.core; /** * This builder to build request */ public interface RequestBuilder { Request.Builder builderGet(String url, StrParam... strParams);
// Path: okhttp/src/main/java/net/qiujuer/common/okhttp/io/IOParam.java // public class IOParam { // public String key; // public File file; // // public IOParam(String key, File file) { // this.key = key; // this.file = file; // } // } // // Path: okhttp/src/main/java/net/qiujuer/common/okhttp/io/StrParam.java // public class StrParam { // public String key; // public String value; // // public StrParam(String key, String value) { // this.key = key; // this.value = value; // } // // public StrParam(String key, int value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, float value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, long value) { // this(key, String.valueOf(value)); // } // // public StrParam(String key, double value) { // this(key, String.valueOf(value)); // } // } // Path: okhttp/src/main/java/net/qiujuer/common/okhttp/core/RequestBuilder.java import net.qiujuer.common.okhttp.io.IOParam; import net.qiujuer.common.okhttp.io.StrParam; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import okhttp3.Request; import okhttp3.RequestBody; /* * Copyright (C) 2014-2016 Qiujuer <qiujuer@live.cn> * WebSite http://www.qiujuer.net * Author Qiujuer * * 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 net.qiujuer.common.okhttp.core; /** * This builder to build request */ public interface RequestBuilder { Request.Builder builderGet(String url, StrParam... strParams);
Request.Builder builderPost(String url, StrParam[] stringStrParams, IOParam[] IOParams);
qiujuer/OkHttpPacker
okhttp/src/main/java/net/qiujuer/common/okhttp/cookie/PersistentCookieStore.java
// Path: okhttp/src/main/java/net/qiujuer/common/okhttp/Util.java // @SuppressWarnings("ALL") // public final class Util { // // private static final String LOG_TAG = "QOK"; // // public static <T> T[] listToParams(List<T> params, Class<T> tClass) { // if (params == null || params.size() == 0) // return (T[]) Array.newInstance(tClass, 0); // // int size = params.size(); // // try { // T[] array = (T[]) Array.newInstance(tClass, size); // return (T[]) params.toArray(array); // } catch (Exception e) { // e.printStackTrace(); // return (T[]) Array.newInstance(tClass, 0); // } // } // // public static StrParam[] mapToStringParams(Map<String, String> params) { // if (params == null) return new StrParam[0]; // int size = params.size(); // if (size == 0) return new StrParam[0]; // StrParam[] res = new StrParam[size]; // Set<Map.Entry<String, String>> entries = params.entrySet(); // int i = 0; // for (Map.Entry<String, String> entry : entries) { // res[i++] = new StrParam(entry.getKey(), entry.getValue()); // } // return res; // } // // public static IOParam[] mapToFileParams(Map<String, File> params) { // if (params == null) return new IOParam[0]; // int size = params.size(); // if (size == 0) return new IOParam[0]; // IOParam[] res = new IOParam[size]; // Set<Map.Entry<String, File>> entries = params.entrySet(); // int i = 0; // for (Map.Entry<String, File> entry : entries) { // res[i++] = new IOParam(entry.getKey(), entry.getValue()); // } // return res; // } // // public static String getFileMimeType(String path) { // FileNameMap fileNameMap = URLConnection.getFileNameMap(); // String contentTypeFor = fileNameMap.getContentTypeFor(path); // if (contentTypeFor == null) { // contentTypeFor = "application/octet-stream"; // } // return contentTypeFor; // } // // public static File getFile(String fileDir, String fileName, String url) { // // check the file dir // if (TextUtils.isEmpty(fileDir)) // throw new NullPointerException("File Dir is not null."); // // // make dir // File dir = new File(fileDir); // if (!dir.exists()) { // dir.mkdirs(); // } // // // check the file name // if (TextUtils.isEmpty(fileName)) { // int separatorIndex = url.lastIndexOf("/"); // fileName = (separatorIndex < 0) ? url : url.substring(separatorIndex + 1, url.length()); // if (TextUtils.isEmpty(fileName) || !fileName.contains(".")) // fileName = String.valueOf(System.currentTimeMillis()) + ".cache"; // } // // return new File(dir, fileName); // } // // public static File makeFile(File file) { // if (file.exists()) { // file.delete(); // } // // if (!file.exists()) { // try { // file.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } // } // return file; // } // // public static String cookieHeader(List<Cookie> cookies) { // StringBuilder cookieHeader = new StringBuilder(); // for (int i = 0, size = cookies.size(); i < size; i++) { // if (i > 0) { // cookieHeader.append("; "); // } // Cookie cookie = cookies.get(i); // cookieHeader.append(cookie.name()).append('=').append(cookie.value()); // } // return cookieHeader.toString(); // } // // // Show log // public static void log(String msg) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(msg)) // Log.d(LOG_TAG, msg); // } // // public static void log(String fromat, Object... strs) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(fromat) && strs != null) // Log.d(LOG_TAG, String.format(fromat, strs)); // } // // // public static void log(String msg, Throwable tr) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(msg)) // Log.d(LOG_TAG, msg, tr); // } // // // Show Error // public static void exception(Exception e) { // if (HttpCore.DEBUG && e != null) // e.printStackTrace(); // } // }
import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import okhttp3.Cookie; import okhttp3.HttpUrl; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import net.qiujuer.common.okhttp.Util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap;
return ret; } @Override public List<HttpUrl> getHttpUrls() { ArrayList<HttpUrl> ret = new ArrayList<HttpUrl>(); for (String key : cookies.keySet()) try { ret.add(new HttpUrl.Builder().host(key).build()); } catch (Exception e) { e.printStackTrace(); } return ret; } /** * Serializes Cookie object into String * * @param cookie cookie to be encoded, can be null * @return cookie encoded as String */ protected String encodeCookie(SerializableHttpCookie cookie) { if (cookie == null) return null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream outputStream = new ObjectOutputStream(os); outputStream.writeObject(cookie); } catch (IOException e) {
// Path: okhttp/src/main/java/net/qiujuer/common/okhttp/Util.java // @SuppressWarnings("ALL") // public final class Util { // // private static final String LOG_TAG = "QOK"; // // public static <T> T[] listToParams(List<T> params, Class<T> tClass) { // if (params == null || params.size() == 0) // return (T[]) Array.newInstance(tClass, 0); // // int size = params.size(); // // try { // T[] array = (T[]) Array.newInstance(tClass, size); // return (T[]) params.toArray(array); // } catch (Exception e) { // e.printStackTrace(); // return (T[]) Array.newInstance(tClass, 0); // } // } // // public static StrParam[] mapToStringParams(Map<String, String> params) { // if (params == null) return new StrParam[0]; // int size = params.size(); // if (size == 0) return new StrParam[0]; // StrParam[] res = new StrParam[size]; // Set<Map.Entry<String, String>> entries = params.entrySet(); // int i = 0; // for (Map.Entry<String, String> entry : entries) { // res[i++] = new StrParam(entry.getKey(), entry.getValue()); // } // return res; // } // // public static IOParam[] mapToFileParams(Map<String, File> params) { // if (params == null) return new IOParam[0]; // int size = params.size(); // if (size == 0) return new IOParam[0]; // IOParam[] res = new IOParam[size]; // Set<Map.Entry<String, File>> entries = params.entrySet(); // int i = 0; // for (Map.Entry<String, File> entry : entries) { // res[i++] = new IOParam(entry.getKey(), entry.getValue()); // } // return res; // } // // public static String getFileMimeType(String path) { // FileNameMap fileNameMap = URLConnection.getFileNameMap(); // String contentTypeFor = fileNameMap.getContentTypeFor(path); // if (contentTypeFor == null) { // contentTypeFor = "application/octet-stream"; // } // return contentTypeFor; // } // // public static File getFile(String fileDir, String fileName, String url) { // // check the file dir // if (TextUtils.isEmpty(fileDir)) // throw new NullPointerException("File Dir is not null."); // // // make dir // File dir = new File(fileDir); // if (!dir.exists()) { // dir.mkdirs(); // } // // // check the file name // if (TextUtils.isEmpty(fileName)) { // int separatorIndex = url.lastIndexOf("/"); // fileName = (separatorIndex < 0) ? url : url.substring(separatorIndex + 1, url.length()); // if (TextUtils.isEmpty(fileName) || !fileName.contains(".")) // fileName = String.valueOf(System.currentTimeMillis()) + ".cache"; // } // // return new File(dir, fileName); // } // // public static File makeFile(File file) { // if (file.exists()) { // file.delete(); // } // // if (!file.exists()) { // try { // file.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } // } // return file; // } // // public static String cookieHeader(List<Cookie> cookies) { // StringBuilder cookieHeader = new StringBuilder(); // for (int i = 0, size = cookies.size(); i < size; i++) { // if (i > 0) { // cookieHeader.append("; "); // } // Cookie cookie = cookies.get(i); // cookieHeader.append(cookie.name()).append('=').append(cookie.value()); // } // return cookieHeader.toString(); // } // // // Show log // public static void log(String msg) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(msg)) // Log.d(LOG_TAG, msg); // } // // public static void log(String fromat, Object... strs) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(fromat) && strs != null) // Log.d(LOG_TAG, String.format(fromat, strs)); // } // // // public static void log(String msg, Throwable tr) { // if (HttpCore.DEBUG && !TextUtils.isEmpty(msg)) // Log.d(LOG_TAG, msg, tr); // } // // // Show Error // public static void exception(Exception e) { // if (HttpCore.DEBUG && e != null) // e.printStackTrace(); // } // } // Path: okhttp/src/main/java/net/qiujuer/common/okhttp/cookie/PersistentCookieStore.java import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import okhttp3.Cookie; import okhttp3.HttpUrl; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import net.qiujuer.common.okhttp.Util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; return ret; } @Override public List<HttpUrl> getHttpUrls() { ArrayList<HttpUrl> ret = new ArrayList<HttpUrl>(); for (String key : cookies.keySet()) try { ret.add(new HttpUrl.Builder().host(key).build()); } catch (Exception e) { e.printStackTrace(); } return ret; } /** * Serializes Cookie object into String * * @param cookie cookie to be encoded, can be null * @return cookie encoded as String */ protected String encodeCookie(SerializableHttpCookie cookie) { if (cookie == null) return null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream outputStream = new ObjectOutputStream(os); outputStream.writeObject(cookie); } catch (IOException e) {
Util.log("IOException in encodeCookie", e);
minnal/autopojo
src/test/java/org/minnal/autopojo/resolver/EnumReoslverTest.java
// Path: src/test/java/org/minnal/autopojo/SimpleEnum.java // public enum SimpleEnum { // // value1, value2, value3 // }
import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import org.minnal.autopojo.SimpleEnum;
/** * */ package org.minnal.autopojo.resolver; /** * @author ganeshs * */ public class EnumReoslverTest { @Test public void shouldGenerateEnum() { EnumResolver resolver = new EnumResolver();
// Path: src/test/java/org/minnal/autopojo/SimpleEnum.java // public enum SimpleEnum { // // value1, value2, value3 // } // Path: src/test/java/org/minnal/autopojo/resolver/EnumReoslverTest.java import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import org.minnal.autopojo.SimpleEnum; /** * */ package org.minnal.autopojo.resolver; /** * @author ganeshs * */ public class EnumReoslverTest { @Test public void shouldGenerateEnum() { EnumResolver resolver = new EnumResolver();
assertEquals(resolver.resolve(SimpleEnum.class, 1), SimpleEnum.value1);
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/cache/CustomRedisCache.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/cache/Constants.java // public static final String REDIS_KEY_SEPARATOR = ":";
import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.Cache; import org.springframework.cache.support.AbstractValueAdaptingCache; import org.springframework.cache.support.SimpleValueWrapper; import java.io.*; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import static org.mskcc.cbio.oncokb.cache.Constants.REDIS_KEY_SEPARATOR;
package org.mskcc.cbio.oncokb.cache; /** * @author Luke Sikina, Hongxin Zhang **/ public abstract class CustomRedisCache extends AbstractValueAdaptingCache { private static final Logger LOG = LoggerFactory.getLogger(CustomRedisCache.class); public static final int INFINITE_TTL = -1; protected final String name; protected final long ttlMinutes; protected final RedissonClient store; /** * Create a new ConcurrentMapCache with the specified name. * @param name the name of the cache */ public CustomRedisCache(String name, RedissonClient client, long ttlMinutes) { super(true); this.name = name; this.store = client; this.ttlMinutes = ttlMinutes; } @Override public final String getName() { return name; } @Override public final RedissonClient getNativeCache() { return this.store; } @Override protected Object lookup(Object key) {
// Path: core/src/main/java/org/mskcc/cbio/oncokb/cache/Constants.java // public static final String REDIS_KEY_SEPARATOR = ":"; // Path: core/src/main/java/org/mskcc/cbio/oncokb/cache/CustomRedisCache.java import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.Cache; import org.springframework.cache.support.AbstractValueAdaptingCache; import org.springframework.cache.support.SimpleValueWrapper; import java.io.*; import java.util.concurrent.TimeUnit; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import static org.mskcc.cbio.oncokb.cache.Constants.REDIS_KEY_SEPARATOR; package org.mskcc.cbio.oncokb.cache; /** * @author Luke Sikina, Hongxin Zhang **/ public abstract class CustomRedisCache extends AbstractValueAdaptingCache { private static final Logger LOG = LoggerFactory.getLogger(CustomRedisCache.class); public static final int INFINITE_TTL = -1; protected final String name; protected final long ttlMinutes; protected final RedissonClient store; /** * Create a new ConcurrentMapCache with the specified name. * @param name the name of the cache */ public CustomRedisCache(String name, RedissonClient client, long ttlMinutes) { super(true); this.name = name; this.store = client; this.ttlMinutes = ttlMinutes; } @Override public final String getName() { return name; } @Override public final RedissonClient getNativeCache() { return this.store; } @Override protected Object lookup(Object key) {
Object value = this.store.getBucket(name + REDIS_KEY_SEPARATOR + key).get();
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/model/OncoKBInfo.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/InfoLevel.java // public class InfoLevel implements Serializable { // private LevelOfEvidence levelOfEvidence; // private String description; // private String htmlDescription; // private String colorHex; // // public InfoLevel(LevelOfEvidence levelOfEvidence) { // this.levelOfEvidence = levelOfEvidence; // this.description = levelOfEvidence.getDescription(); // this.htmlDescription = levelOfEvidence.getHtmlDescription(); // this.colorHex = levelOfEvidence.getColorHex(); // } // // public LevelOfEvidence getLevelOfEvidence() { // return levelOfEvidence; // } // // public String getDescription() { // return description; // } // // public String getHtmlDescription() { // return htmlDescription; // } // // public String getColorHex() { // return colorHex; // } // }
import org.mskcc.cbio.oncokb.apiModels.InfoLevel; import org.mskcc.cbio.oncokb.util.*; import java.io.Serializable; import java.util.List; import static org.mskcc.cbio.oncokb.Constants.IS_PUBLIC_INSTANCE; import static org.mskcc.cbio.oncokb.Constants.PUBLIC_API_VERSION;
package org.mskcc.cbio.oncokb.model; /** * Created by Hongxin Zhang on 7/13/18. */ public class OncoKBInfo implements Serializable { String oncoTreeVersion; String ncitVersion;
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/InfoLevel.java // public class InfoLevel implements Serializable { // private LevelOfEvidence levelOfEvidence; // private String description; // private String htmlDescription; // private String colorHex; // // public InfoLevel(LevelOfEvidence levelOfEvidence) { // this.levelOfEvidence = levelOfEvidence; // this.description = levelOfEvidence.getDescription(); // this.htmlDescription = levelOfEvidence.getHtmlDescription(); // this.colorHex = levelOfEvidence.getColorHex(); // } // // public LevelOfEvidence getLevelOfEvidence() { // return levelOfEvidence; // } // // public String getDescription() { // return description; // } // // public String getHtmlDescription() { // return htmlDescription; // } // // public String getColorHex() { // return colorHex; // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/model/OncoKBInfo.java import org.mskcc.cbio.oncokb.apiModels.InfoLevel; import org.mskcc.cbio.oncokb.util.*; import java.io.Serializable; import java.util.List; import static org.mskcc.cbio.oncokb.Constants.IS_PUBLIC_INSTANCE; import static org.mskcc.cbio.oncokb.Constants.PUBLIC_API_VERSION; package org.mskcc.cbio.oncokb.model; /** * Created by Hongxin Zhang on 7/13/18. */ public class OncoKBInfo implements Serializable { String oncoTreeVersion; String ncitVersion;
List<InfoLevel> levels;
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/apiModels/annotation/AnnotationQuery.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/model/EvidenceType.java // public enum EvidenceType { // GENE_SUMMARY("Gene summary"), // MUTATION_SUMMARY("Mutation summary"), // TUMOR_TYPE_SUMMARY("Tumor type summary"), // GENE_TUMOR_TYPE_SUMMARY("Gene tumor type summary"), // PROGNOSTIC_SUMMARY("Prognostic summary"), // DIAGNOSTIC_SUMMARY("Diagnostic summary"), // GENE_BACKGROUND("Gene background"), // ONCOGENIC("Oncogenic"), // MUTATION_EFFECT("Mutation effect"), // VUS("Variant of unknown significance"), // PROGNOSTIC_IMPLICATION("Prognostic implications"), // DIAGNOSTIC_IMPLICATION("Diagnostic implications"), // STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_SENSITIVITY("Standard therapeutic implications for drug sensitivity"), // STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_RESISTANCE("Standard therapeutic implications for drug resistance"), // INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_SENSITIVITY("Investigational therapeutic implications for drug sensitivity"), // INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_RESISTANCE("Investigational therapeutic implications for drug resistance"); // // EvidenceType(String label) { // this.label = label; // } // // private final String label; // // public String label() { // return label; // } // }
import org.mskcc.cbio.oncokb.model.EvidenceType; import org.mskcc.cbio.oncokb.model.ReferenceGenome; import java.util.HashSet; import java.util.Objects; import java.util.Set;
package org.mskcc.cbio.oncokb.apiModels.annotation; /** * Created by Hongxin Zhang on 2019-03-25. */ public class AnnotationQuery implements java.io.Serializable{ private String id; //Optional, This id is passed from request. The identifier used to distinguish the query private ReferenceGenome referenceGenome = ReferenceGenome.GRCh37; private String tumorType;
// Path: core/src/main/java/org/mskcc/cbio/oncokb/model/EvidenceType.java // public enum EvidenceType { // GENE_SUMMARY("Gene summary"), // MUTATION_SUMMARY("Mutation summary"), // TUMOR_TYPE_SUMMARY("Tumor type summary"), // GENE_TUMOR_TYPE_SUMMARY("Gene tumor type summary"), // PROGNOSTIC_SUMMARY("Prognostic summary"), // DIAGNOSTIC_SUMMARY("Diagnostic summary"), // GENE_BACKGROUND("Gene background"), // ONCOGENIC("Oncogenic"), // MUTATION_EFFECT("Mutation effect"), // VUS("Variant of unknown significance"), // PROGNOSTIC_IMPLICATION("Prognostic implications"), // DIAGNOSTIC_IMPLICATION("Diagnostic implications"), // STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_SENSITIVITY("Standard therapeutic implications for drug sensitivity"), // STANDARD_THERAPEUTIC_IMPLICATIONS_FOR_DRUG_RESISTANCE("Standard therapeutic implications for drug resistance"), // INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_SENSITIVITY("Investigational therapeutic implications for drug sensitivity"), // INVESTIGATIONAL_THERAPEUTIC_IMPLICATIONS_DRUG_RESISTANCE("Investigational therapeutic implications for drug resistance"); // // EvidenceType(String label) { // this.label = label; // } // // private final String label; // // public String label() { // return label; // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/annotation/AnnotationQuery.java import org.mskcc.cbio.oncokb.model.EvidenceType; import org.mskcc.cbio.oncokb.model.ReferenceGenome; import java.util.HashSet; import java.util.Objects; import java.util.Set; package org.mskcc.cbio.oncokb.apiModels.annotation; /** * Created by Hongxin Zhang on 2019-03-25. */ public class AnnotationQuery implements java.io.Serializable{ private String id; //Optional, This id is passed from request. The identifier used to distinguish the query private ReferenceGenome referenceGenome = ReferenceGenome.GRCh37; private String tumorType;
private Set<EvidenceType> evidenceTypes = new HashSet<>();
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName;
return StringUtils.join(lines, "\n"); } public static List<String> readTrimedLinesStream(InputStream is) throws IOException { return readLinesStream(is, true); } /** * read a stream and return lines * @param is * @return * @throws IOException */ public static List<String> readLinesStream(InputStream is, boolean trim) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); String line; while ((line = in.readLine()) != null) { if (trim) { line = line.trim(); } if (!line.isEmpty()) lines.add(line); } in.close(); return lines; }
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName; return StringUtils.join(lines, "\n"); } public static List<String> readTrimedLinesStream(InputStream is) throws IOException { return readLinesStream(is, true); } /** * read a stream and return lines * @param is * @return * @throws IOException */ public static List<String> readLinesStream(InputStream is, boolean trim) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); String line; while ((line = in.readLine()) != null) { if (trim) { line = line.trim(); } if (!line.isEmpty()) lines.add(line); } in.close(); return lines; }
public static String getFileName(FileName fileName, FileExtension fileExtension) {
oncokb/oncokb
web/src/main/java/org/mskcc/cbio/oncokb/api/pub/v1/InfoApiController.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/model/OncoKBInfo.java // public class OncoKBInfo implements Serializable { // String oncoTreeVersion; // String ncitVersion; // List<InfoLevel> levels; // Version dataVersion; // String apiVersion; // Boolean publicInstance; // // public OncoKBInfo() { // Info info = CacheUtils.getInfo(); // // this.oncoTreeVersion = info.getOncoTreeVersion(); // this.ncitVersion = info.getNcitVersion(); // this.levels = LevelUtils.getInfoLevels(); // // Version dataVersion = new Version(); // dataVersion.setVersion(MainUtils.getDataVersion()); // dataVersion.setDate(MainUtils.getDataVersionDate()); // // this.dataVersion = dataVersion; // this.apiVersion = PUBLIC_API_VERSION; // // String isPublicInstance = PropertiesUtils.getProperties(IS_PUBLIC_INSTANCE); // // if (isPublicInstance != null && Boolean.valueOf(isPublicInstance)) { // this.publicInstance = true; // } else { // this.publicInstance = false; // } // } // // public String getOncoTreeVersion() { // return oncoTreeVersion; // } // // public String getNcitVersion() { // return ncitVersion; // } // // public List<InfoLevel> getLevels() { // return levels; // } // // public Version getDataVersion() { // return dataVersion; // } // // public Boolean getPublicInstance() { // return publicInstance; // } // // public String getApiVersion() { // return apiVersion; // } // }
import org.mskcc.cbio.oncokb.cache.CacheFetcher; import org.mskcc.cbio.oncokb.model.OncoKBInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller;
package org.mskcc.cbio.oncokb.api.pub.v1; /** * Created by Hongxin Zhang on 7/13/18. */ @Controller public class InfoApiController implements InfoApi { @Autowired CacheFetcher cacheFetcher; @Override
// Path: core/src/main/java/org/mskcc/cbio/oncokb/model/OncoKBInfo.java // public class OncoKBInfo implements Serializable { // String oncoTreeVersion; // String ncitVersion; // List<InfoLevel> levels; // Version dataVersion; // String apiVersion; // Boolean publicInstance; // // public OncoKBInfo() { // Info info = CacheUtils.getInfo(); // // this.oncoTreeVersion = info.getOncoTreeVersion(); // this.ncitVersion = info.getNcitVersion(); // this.levels = LevelUtils.getInfoLevels(); // // Version dataVersion = new Version(); // dataVersion.setVersion(MainUtils.getDataVersion()); // dataVersion.setDate(MainUtils.getDataVersionDate()); // // this.dataVersion = dataVersion; // this.apiVersion = PUBLIC_API_VERSION; // // String isPublicInstance = PropertiesUtils.getProperties(IS_PUBLIC_INSTANCE); // // if (isPublicInstance != null && Boolean.valueOf(isPublicInstance)) { // this.publicInstance = true; // } else { // this.publicInstance = false; // } // } // // public String getOncoTreeVersion() { // return oncoTreeVersion; // } // // public String getNcitVersion() { // return ncitVersion; // } // // public List<InfoLevel> getLevels() { // return levels; // } // // public Version getDataVersion() { // return dataVersion; // } // // public Boolean getPublicInstance() { // return publicInstance; // } // // public String getApiVersion() { // return apiVersion; // } // } // Path: web/src/main/java/org/mskcc/cbio/oncokb/api/pub/v1/InfoApiController.java import org.mskcc.cbio.oncokb.cache.CacheFetcher; import org.mskcc.cbio.oncokb.model.OncoKBInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; package org.mskcc.cbio.oncokb.api.pub.v1; /** * Created by Hongxin Zhang on 7/13/18. */ @Controller public class InfoApiController implements InfoApi { @Autowired CacheFetcher cacheFetcher; @Override
public ResponseEntity<OncoKBInfo> infoGet() {
oncokb/oncokb
web/src/main/java/org/mskcc/cbio/oncokb/api/pub/v1/DrugsApiController.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/dao/DrugDao.java // public interface DrugDao extends GenericDao<Drug, Integer> { // Drug findDrugById(Integer id); // /** // * // * @param drugName // * @return // */ // Drug findDrugByName(String drugName); // // /** // * // * @param synonym // * @return // */ // List<Drug> findDrugBySynonym(String synonym); // // /** // * // * @param ncitCode // * @return // */ // Drug findDrugByNcitCode(String ncitCode); // // @Override // void save(Drug drug); // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/DrugUtils.java // public class DrugUtils { // public static Set<Drug> getDrugsByNames(Set<String> names, Boolean fuzzy) { // Set<Drug> result = new HashSet<>(); // if (fuzzy == null) { // fuzzy = false; // } // if (names != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // for (String name : names) { // if (stringInSet(Collections.singleton(drug.getDrugName()), name, fuzzy)) { // result.add(drug); // } // } // } // } // return result; // } // // public static Set<Drug> getDrugsBySynonyms(Set<String> synonyms, Boolean fuzzy) { // Set<Drug> result = new HashSet<>(); // if (fuzzy == null) { // fuzzy = false; // } // if (synonyms != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // for (String synonym : synonyms) { // if (stringInSet(drug.getSynonyms(), synonym, fuzzy)) { // result.add(drug); // } // } // } // } // return result; // } // // public static Drug getDrugByNcitCode(String code) { // if (code != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // if (drug.getNcitCode() != null && drug.getNcitCode().equals(code)) { // return drug; // } // } // } // return null; // } // // public static Set<Drug> getAllDrugs() { // Set<Drug> drugs = new HashSet<>(); // drugs = CacheUtils.getAllDrugs(); // return drugs; // } // // private static Boolean stringInSet(Set<String> strings, String search, Boolean fuzzy) { // if (strings != null) { // for (String string : strings) { // if (fuzzy) { // if (StringUtils.containsIgnoreCase(string, search)) { // return true; // } // } else { // if (string.equals(search)) { // return true; // } // } // } // } // return false; // } // // public static void updateDrugName(Drug drug, String newDrugName) { // drug.getSynonyms().remove(newDrugName); // drug.getSynonyms().add(drug.getDrugName()); // drug.setDrugName(newDrugName); // } // }
import io.swagger.annotations.ApiParam; import org.apache.commons.collections.CollectionUtils; import org.mskcc.cbio.oncokb.bo.DrugBo; import org.mskcc.cbio.oncokb.dao.DrugDao; import org.mskcc.cbio.oncokb.model.Drug; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.DrugUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.io.IOException; import java.util.*;
package org.mskcc.cbio.oncokb.api.pub.v1; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-14T18:47:53.991Z") @Controller public class DrugsApiController implements DrugsApi { public ResponseEntity<List<Drug>> drugsGet() { DrugBo drugBo = ApplicationContextSingleton.getDrugBo();
// Path: core/src/main/java/org/mskcc/cbio/oncokb/dao/DrugDao.java // public interface DrugDao extends GenericDao<Drug, Integer> { // Drug findDrugById(Integer id); // /** // * // * @param drugName // * @return // */ // Drug findDrugByName(String drugName); // // /** // * // * @param synonym // * @return // */ // List<Drug> findDrugBySynonym(String synonym); // // /** // * // * @param ncitCode // * @return // */ // Drug findDrugByNcitCode(String ncitCode); // // @Override // void save(Drug drug); // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/DrugUtils.java // public class DrugUtils { // public static Set<Drug> getDrugsByNames(Set<String> names, Boolean fuzzy) { // Set<Drug> result = new HashSet<>(); // if (fuzzy == null) { // fuzzy = false; // } // if (names != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // for (String name : names) { // if (stringInSet(Collections.singleton(drug.getDrugName()), name, fuzzy)) { // result.add(drug); // } // } // } // } // return result; // } // // public static Set<Drug> getDrugsBySynonyms(Set<String> synonyms, Boolean fuzzy) { // Set<Drug> result = new HashSet<>(); // if (fuzzy == null) { // fuzzy = false; // } // if (synonyms != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // for (String synonym : synonyms) { // if (stringInSet(drug.getSynonyms(), synonym, fuzzy)) { // result.add(drug); // } // } // } // } // return result; // } // // public static Drug getDrugByNcitCode(String code) { // if (code != null) { // Set<Drug> drugs = getAllDrugs(); // for (Drug drug : drugs) { // if (drug.getNcitCode() != null && drug.getNcitCode().equals(code)) { // return drug; // } // } // } // return null; // } // // public static Set<Drug> getAllDrugs() { // Set<Drug> drugs = new HashSet<>(); // drugs = CacheUtils.getAllDrugs(); // return drugs; // } // // private static Boolean stringInSet(Set<String> strings, String search, Boolean fuzzy) { // if (strings != null) { // for (String string : strings) { // if (fuzzy) { // if (StringUtils.containsIgnoreCase(string, search)) { // return true; // } // } else { // if (string.equals(search)) { // return true; // } // } // } // } // return false; // } // // public static void updateDrugName(Drug drug, String newDrugName) { // drug.getSynonyms().remove(newDrugName); // drug.getSynonyms().add(drug.getDrugName()); // drug.setDrugName(newDrugName); // } // } // Path: web/src/main/java/org/mskcc/cbio/oncokb/api/pub/v1/DrugsApiController.java import io.swagger.annotations.ApiParam; import org.apache.commons.collections.CollectionUtils; import org.mskcc.cbio.oncokb.bo.DrugBo; import org.mskcc.cbio.oncokb.dao.DrugDao; import org.mskcc.cbio.oncokb.model.Drug; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.DrugUtils; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.io.IOException; import java.util.*; package org.mskcc.cbio.oncokb.api.pub.v1; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-10-14T18:47:53.991Z") @Controller public class DrugsApiController implements DrugsApi { public ResponseEntity<List<Drug>> drugsGet() { DrugBo drugBo = ApplicationContextSingleton.getDrugBo();
List<Drug> drugs = new ArrayList<>(DrugUtils.getAllDrugs());
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/model/Geneset.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/serializer/SetGeneInGenesetConverter.java // public class SetGeneInGenesetConverter extends StdConverter<Set<Gene>, Set<Gene>> { // @Override // public Set<Gene> convert(Set<Gene> genes) { // Set<Gene> newGenes = new HashSet<>(); // for (Gene gene : genes) { // Gene newGene = new Gene(); // newGene.setGeneAliases(newGene.getGeneAliases()); // newGene.setHugoSymbol(gene.getHugoSymbol()); // newGene.setEntrezGeneId(gene.getEntrezGeneId()); // newGene.setOncogene(gene.getOncogene()); // newGene.setTSG(gene.getTSG()); // newGene.setGrch37Isoform(gene.getGrch37Isoform()); // newGene.setGrch37RefSeq(gene.getGrch37RefSeq()); // newGene.setGrch38Isoform(gene.getGrch38Isoform()); // newGene.setGrch38RefSeq(gene.getGrch38RefSeq()); // newGenes.add(newGene); // } // return newGenes; // } // }
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.mskcc.cbio.oncokb.serializer.SetGeneInGenesetConverter; import javax.persistence.*; import java.util.Objects; import java.util.Set;
package org.mskcc.cbio.oncokb.model; /** * Created by Hongxin Zhang on 2019-08-08. */ @NamedQueries({ @NamedQuery( name = "findGenesetByName", query = "select g from Geneset g where g.name=?" ), @NamedQuery( name = "findGenesetByUUID", query = "select g from Geneset g where g.uuid=?" ), }) @Entity @Table(name = "geneset") public class Geneset implements java.io.Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) private String name; @Column(length = 40, nullable = false) private String uuid; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "geneset_gene", joinColumns = { @JoinColumn(name = "geneset_id", updatable = false, nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "entrez_gene_id", updatable = false, nullable = false) })
// Path: core/src/main/java/org/mskcc/cbio/oncokb/serializer/SetGeneInGenesetConverter.java // public class SetGeneInGenesetConverter extends StdConverter<Set<Gene>, Set<Gene>> { // @Override // public Set<Gene> convert(Set<Gene> genes) { // Set<Gene> newGenes = new HashSet<>(); // for (Gene gene : genes) { // Gene newGene = new Gene(); // newGene.setGeneAliases(newGene.getGeneAliases()); // newGene.setHugoSymbol(gene.getHugoSymbol()); // newGene.setEntrezGeneId(gene.getEntrezGeneId()); // newGene.setOncogene(gene.getOncogene()); // newGene.setTSG(gene.getTSG()); // newGene.setGrch37Isoform(gene.getGrch37Isoform()); // newGene.setGrch37RefSeq(gene.getGrch37RefSeq()); // newGene.setGrch38Isoform(gene.getGrch38Isoform()); // newGene.setGrch38RefSeq(gene.getGrch38RefSeq()); // newGenes.add(newGene); // } // return newGenes; // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/model/Geneset.java import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.mskcc.cbio.oncokb.serializer.SetGeneInGenesetConverter; import javax.persistence.*; import java.util.Objects; import java.util.Set; package org.mskcc.cbio.oncokb.model; /** * Created by Hongxin Zhang on 2019-08-08. */ @NamedQueries({ @NamedQuery( name = "findGenesetByName", query = "select g from Geneset g where g.name=?" ), @NamedQuery( name = "findGenesetByUUID", query = "select g from Geneset g where g.uuid=?" ), }) @Entity @Table(name = "geneset") public class Geneset implements java.io.Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) private String name; @Column(length = 40, nullable = false) private String uuid; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "geneset_gene", joinColumns = { @JoinColumn(name = "geneset_id", updatable = false, nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "entrez_gene_id", updatable = false, nullable = false) })
@JsonSerialize(converter = SetGeneInGenesetConverter.class)
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/util/GitHubUtils.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // }
import com.sun.mail.iap.ByteArray; import org.apache.commons.io.IOUtils; import org.kohsuke.github.GHBlob; import org.kohsuke.github.GHContent; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.mskcc.cbio.oncokb.apiModels.download.DownloadAvailability; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.mskcc.cbio.oncokb.util.FileUtils.getFileName;
public static byte[] getOncoKBDataInBytes(String version, String fileName) throws HttpClientErrorException, IOException, NoPropertyException { GHBlob ghBlob = getGHBlob(version, fileName); return IOUtils.toByteArray(ghBlob.read()); } private static GHBlob getGHBlob(String version, String fileName) throws IOException, NoPropertyException { GHRepository repo = getOncoKBDataRepo(); List<GHContent> contents = new ArrayList<>(); try { contents = repo.getDirectoryContent("/RELEASE/" + version); } catch (Exception e) { // in this case, is the directory is not available. throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } Optional<GHContent> matchedContent = contents.stream().filter(content -> content.getName().equals(fileName)).findFirst(); if (matchedContent.isPresent()) { String sha = matchedContent.get().getSha(); GHBlob ghBlob = repo.getBlob(sha); return ghBlob; } else { throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } } public static String getOncoKBSqlDumpFileName(String version) { if (version == null) { return ""; }
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/GitHubUtils.java import com.sun.mail.iap.ByteArray; import org.apache.commons.io.IOUtils; import org.kohsuke.github.GHBlob; import org.kohsuke.github.GHContent; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.mskcc.cbio.oncokb.apiModels.download.DownloadAvailability; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.mskcc.cbio.oncokb.util.FileUtils.getFileName; public static byte[] getOncoKBDataInBytes(String version, String fileName) throws HttpClientErrorException, IOException, NoPropertyException { GHBlob ghBlob = getGHBlob(version, fileName); return IOUtils.toByteArray(ghBlob.read()); } private static GHBlob getGHBlob(String version, String fileName) throws IOException, NoPropertyException { GHRepository repo = getOncoKBDataRepo(); List<GHContent> contents = new ArrayList<>(); try { contents = repo.getDirectoryContent("/RELEASE/" + version); } catch (Exception e) { // in this case, is the directory is not available. throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } Optional<GHContent> matchedContent = contents.stream().filter(content -> content.getName().equals(fileName)).findFirst(); if (matchedContent.isPresent()) { String sha = matchedContent.get().getSha(); GHBlob ghBlob = repo.getBlob(sha); return ghBlob; } else { throw new HttpClientErrorException(HttpStatus.NOT_FOUND); } } public static String getOncoKBSqlDumpFileName(String version) { if (version == null) { return ""; }
return "oncokb_" + version.replace(".", "_") + ".sql" + FileExtension.GZ.getExtension();
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/util/GitHubUtils.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // }
import com.sun.mail.iap.ByteArray; import org.apache.commons.io.IOUtils; import org.kohsuke.github.GHBlob; import org.kohsuke.github.GHContent; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.mskcc.cbio.oncokb.apiModels.download.DownloadAvailability; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.mskcc.cbio.oncokb.util.FileUtils.getFileName;
private static Boolean checkFileNameExists(List<GHContent> files, String fileName, boolean ignoreCase) { return files .stream() .filter(file -> ignoreCase ? file.getName().equalsIgnoreCase(fileName) : file.getName().equals(fileName)) .findFirst() .isPresent(); } private static Boolean checkSqlDumpExists(List<GHContent> files, String version) { return files .stream() .filter(file -> file.getName().startsWith(getOncoKBSqlDumpFileName(version))) .findFirst() .isPresent(); } public static List<DownloadAvailability> getDownloadAvailability() throws HttpClientErrorException, IOException, NoPropertyException { List<DownloadAvailability> downloadAvailabilities = new ArrayList<>(); GHRepository repo = getOncoKBDataRepo(); List<GHContent> versions = repo.getDirectoryContent("/RELEASE/"); for (GHContent version : versions) { List<GHContent> files = new ArrayList<>(); try { files = repo.getDirectoryContent("/RELEASE/" + version.getName()); } catch (Exception e) { // Preventing the item is not a directory, but we want to continue indexing the items. continue; } DownloadAvailability downloadAvailability = new DownloadAvailability(version.getName());
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/download/FileExtension.java // public enum FileExtension { // JSON(".json"), TEXT(".txt"), MARK_DOWN(".md"), GZ(".gz"); // String extension; // // FileExtension(String extension) { // this.extension = extension; // } // // public String getExtension() { // return extension; // } // // public void setExtension(String extension) { // this.extension = extension; // } // } // // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/util/GitHubUtils.java import com.sun.mail.iap.ByteArray; import org.apache.commons.io.IOUtils; import org.kohsuke.github.GHBlob; import org.kohsuke.github.GHContent; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.mskcc.cbio.oncokb.apiModels.download.DownloadAvailability; import org.mskcc.cbio.oncokb.apiModels.download.FileExtension; import org.mskcc.cbio.oncokb.apiModels.download.FileName; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.mskcc.cbio.oncokb.util.FileUtils.getFileName; private static Boolean checkFileNameExists(List<GHContent> files, String fileName, boolean ignoreCase) { return files .stream() .filter(file -> ignoreCase ? file.getName().equalsIgnoreCase(fileName) : file.getName().equals(fileName)) .findFirst() .isPresent(); } private static Boolean checkSqlDumpExists(List<GHContent> files, String version) { return files .stream() .filter(file -> file.getName().startsWith(getOncoKBSqlDumpFileName(version))) .findFirst() .isPresent(); } public static List<DownloadAvailability> getDownloadAvailability() throws HttpClientErrorException, IOException, NoPropertyException { List<DownloadAvailability> downloadAvailabilities = new ArrayList<>(); GHRepository repo = getOncoKBDataRepo(); List<GHContent> versions = repo.getDirectoryContent("/RELEASE/"); for (GHContent version : versions) { List<GHContent> files = new ArrayList<>(); try { files = repo.getDirectoryContent("/RELEASE/" + version.getName()); } catch (Exception e) { // Preventing the item is not a directory, but we want to continue indexing the items. continue; } DownloadAvailability downloadAvailability = new DownloadAvailability(version.getName());
if (checkFileNameExists(files, getFileName(FileName.ALL_ANNOTATED_VARIANTS, FileExtension.TEXT))) {
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/model/IndicatorQueryResp.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/MutationEffectResp.java // public class MutationEffectResp implements Serializable { // String knownEffect = ""; // String description = ""; // Citations citations = new Citations(); // // public String getKnownEffect() { // return knownEffect; // } // // public void setKnownEffect(String knownEffect) { // this.knownEffect = knownEffect; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Citations getCitations() { // return citations; // } // // public void setCitations(Citations citations) { // this.citations = citations; // } // }
import org.mskcc.cbio.oncokb.apiModels.Implication; import org.mskcc.cbio.oncokb.apiModels.MutationEffectResp; import java.util.ArrayList; import java.util.List;
package org.mskcc.cbio.oncokb.model; /** * TumorType generated by hbm2java */ public class IndicatorQueryResp implements java.io.Serializable { private Query query; private Boolean geneExist; private Boolean variantExist; private Boolean alleleExist; private String oncogenic;
// Path: core/src/main/java/org/mskcc/cbio/oncokb/apiModels/MutationEffectResp.java // public class MutationEffectResp implements Serializable { // String knownEffect = ""; // String description = ""; // Citations citations = new Citations(); // // public String getKnownEffect() { // return knownEffect; // } // // public void setKnownEffect(String knownEffect) { // this.knownEffect = knownEffect; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public Citations getCitations() { // return citations; // } // // public void setCitations(Citations citations) { // this.citations = citations; // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/model/IndicatorQueryResp.java import org.mskcc.cbio.oncokb.apiModels.Implication; import org.mskcc.cbio.oncokb.apiModels.MutationEffectResp; import java.util.ArrayList; import java.util.List; package org.mskcc.cbio.oncokb.model; /** * TumorType generated by hbm2java */ public class IndicatorQueryResp implements java.io.Serializable { private Query query; private Boolean geneExist; private Boolean variantExist; private Boolean alleleExist; private String oncogenic;
private MutationEffectResp mutationEffect;
oncokb/oncokb
core/src/main/java/org/mskcc/cbio/oncokb/importer/ChangeHugoSymbol.java
// Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public class FileUtils { // private FileUtils() { // throw new AssertionError(); // } // // /** // * read local files and return content // * @param pathToFile // * @return // * @throws IOException // */ // public static String readLocal(String pathToFile) throws IOException { // return readStream(new FileInputStream(pathToFile)); // } // // /** // * return remote files and return content // * @param urlToFile // * @return // * @throws IOException // */ // public static String readRemote(String urlToFile) throws IOException { // URL url = new URL(urlToFile); // return readStream(url.openStream()); // } // // public static String readMSKPortal(String urlToFile) throws IOException { // URL myURL = new URL(urlToFile); // HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); // myURLConnection.setRequestProperty ("Authorization", "Bearer " + PropertiesUtils.getProperties("cbioportal.token")); // myURLConnection.setRequestMethod("GET"); // return readStream(myURLConnection.getInputStream()); // } // // public static String readPublicOncoKBRemote(String urlToFile) throws IOException { // URL myURL = new URL(urlToFile); // HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); // myURLConnection.setRequestProperty ("Authorization", "Bearer " + PropertiesUtils.getProperties("public_oncokb.token")); // myURLConnection.setRequestMethod("GET"); // return readStream(myURLConnection.getInputStream()); // } // // /** // * read a stream and return content // * @param is // * @return // * @throws IOException // */ // public static String readStream(InputStream is) throws IOException { // List<String> lines = readTrimedLinesStream(is); // return StringUtils.join(lines, "\n"); // } // // public static List<String> readTrimedLinesStream(InputStream is) throws IOException { // return readLinesStream(is, true); // } // // /** // * read a stream and return lines // * @param is // * @return // * @throws IOException // */ // public static List<String> readLinesStream(InputStream is, boolean trim) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); // // List<String> lines = new ArrayList<String>(); // String line; // while ((line = in.readLine()) != null) { // if (trim) { // line = line.trim(); // } // if (!line.isEmpty()) // lines.add(line); // } // in.close(); // // return lines; // } // // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // } // }
import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.FileUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; import java.io.IOException; import java.util.List;
package org.mskcc.cbio.oncokb.importer; public class ChangeHugoSymbol { private ChangeHugoSymbol() { throw new AssertionError(); } private static final String CHANGE_HUGO_FILE = "/data/change-hugo-symbol.txt"; public static void main(String[] args) throws IOException {
// Path: core/src/main/java/org/mskcc/cbio/oncokb/util/FileUtils.java // public class FileUtils { // private FileUtils() { // throw new AssertionError(); // } // // /** // * read local files and return content // * @param pathToFile // * @return // * @throws IOException // */ // public static String readLocal(String pathToFile) throws IOException { // return readStream(new FileInputStream(pathToFile)); // } // // /** // * return remote files and return content // * @param urlToFile // * @return // * @throws IOException // */ // public static String readRemote(String urlToFile) throws IOException { // URL url = new URL(urlToFile); // return readStream(url.openStream()); // } // // public static String readMSKPortal(String urlToFile) throws IOException { // URL myURL = new URL(urlToFile); // HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); // myURLConnection.setRequestProperty ("Authorization", "Bearer " + PropertiesUtils.getProperties("cbioportal.token")); // myURLConnection.setRequestMethod("GET"); // return readStream(myURLConnection.getInputStream()); // } // // public static String readPublicOncoKBRemote(String urlToFile) throws IOException { // URL myURL = new URL(urlToFile); // HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); // myURLConnection.setRequestProperty ("Authorization", "Bearer " + PropertiesUtils.getProperties("public_oncokb.token")); // myURLConnection.setRequestMethod("GET"); // return readStream(myURLConnection.getInputStream()); // } // // /** // * read a stream and return content // * @param is // * @return // * @throws IOException // */ // public static String readStream(InputStream is) throws IOException { // List<String> lines = readTrimedLinesStream(is); // return StringUtils.join(lines, "\n"); // } // // public static List<String> readTrimedLinesStream(InputStream is) throws IOException { // return readLinesStream(is, true); // } // // /** // * read a stream and return lines // * @param is // * @return // * @throws IOException // */ // public static List<String> readLinesStream(InputStream is, boolean trim) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); // // List<String> lines = new ArrayList<String>(); // String line; // while ((line = in.readLine()) != null) { // if (trim) { // line = line.trim(); // } // if (!line.isEmpty()) // lines.add(line); // } // in.close(); // // return lines; // } // // public static String getFileName(FileName fileName, FileExtension fileExtension) { // return fileName.getName() + fileExtension.getExtension(); // } // } // Path: core/src/main/java/org/mskcc/cbio/oncokb/importer/ChangeHugoSymbol.java import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton; import org.mskcc.cbio.oncokb.util.FileUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; import java.io.IOException; import java.util.List; package org.mskcc.cbio.oncokb.importer; public class ChangeHugoSymbol { private ChangeHugoSymbol() { throw new AssertionError(); } private static final String CHANGE_HUGO_FILE = "/data/change-hugo-symbol.txt"; public static void main(String[] args) throws IOException {
List<String> lines = FileUtils.readTrimedLinesStream(
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorMultiCastThroughputTest.java
// Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // }
import com.lmax.disruptor.support.Operation; import com.lmax.disruptor.support.ValueEvent; import com.lmax.disruptor.support.ValueMutationEventHandler; import com.lmax.disruptor.support.ValueMutationQueueProcessor; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * <pre> * * MultiCast a series of items between 1 publisher and 3 event processors. * * +-----+ * +----->| EP1 | * | +-----+ * | * +----+ +-----+ * | P1 |--->| EP2 | * +----+ +-----+ * | * | +-----+ * +----->| EP3 | * +-----+ * * * Queue Based: * ============ * take * put +====+ +-----+ * +----->| Q1 |<---| EP1 | * | +====+ +-----+ * | * +----+ +====+ +-----+ * | P1 |--->| Q2 |<---| EP2 | * +----+ +====+ +-----+ * | * | +====+ +-----+ * +----->| Q3 |<---| EP3 | * +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * Q2 - Queue 2 * Q3 - Queue 3 * EP1 - EventProcessor 1 * EP2 - EventProcessor 2 * EP3 - EventProcessor 3 * * * Disruptor: * ========== * track to prevent wrap * +--------------------+----------+----------+ * | | | | * | v v v * +----+ +====+ +====+ +-----+ +-----+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | | EP2 | | EP3 | * +----+ +====+ +====+ +-----+ +-----+ +-----+ * claim get ^ | | | * | | | | * +---------+----------+----------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * EP2 - EventProcessor 2 * EP3 - EventProcessor 3 * * </pre> */ public final class OnePublisherToThreeProcessorMultiCastThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_EVENT_PROCESSORS = 3; private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newFixedThreadPool(NUM_EVENT_PROCESSORS); private final long[] results = new long[NUM_EVENT_PROCESSORS]; { for (long i = 0; i < ITERATIONS; i++) { results[0] = Operation.ADDITION.op(results[0], i); results[1] = Operation.SUBTRACTION.op(results[1], i); results[2] = Operation.AND.op(results[2], i); } } /////////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("unchecked") private final BlockingQueue<Long>[] blockingQueues = new BlockingQueue[NUM_EVENT_PROCESSORS]; { blockingQueues[0] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); blockingQueues[1] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); blockingQueues[2] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); } private final ValueMutationQueueProcessor[] queueProcessors = new ValueMutationQueueProcessor[NUM_EVENT_PROCESSORS]; { queueProcessors[0] = new ValueMutationQueueProcessor(blockingQueues[0], Operation.ADDITION, ITERATIONS - 1); queueProcessors[1] = new ValueMutationQueueProcessor(blockingQueues[1], Operation.SUBTRACTION, ITERATIONS - 1); queueProcessors[2] = new ValueMutationQueueProcessor(blockingQueues[2], Operation.AND, ITERATIONS - 1); } ///////////////////////////////////////////////////////////////////////////////////////////////
// Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // } // Path: src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorMultiCastThroughputTest.java import com.lmax.disruptor.support.Operation; import com.lmax.disruptor.support.ValueEvent; import com.lmax.disruptor.support.ValueMutationEventHandler; import com.lmax.disruptor.support.ValueMutationQueueProcessor; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * <pre> * * MultiCast a series of items between 1 publisher and 3 event processors. * * +-----+ * +----->| EP1 | * | +-----+ * | * +----+ +-----+ * | P1 |--->| EP2 | * +----+ +-----+ * | * | +-----+ * +----->| EP3 | * +-----+ * * * Queue Based: * ============ * take * put +====+ +-----+ * +----->| Q1 |<---| EP1 | * | +====+ +-----+ * | * +----+ +====+ +-----+ * | P1 |--->| Q2 |<---| EP2 | * +----+ +====+ +-----+ * | * | +====+ +-----+ * +----->| Q3 |<---| EP3 | * +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * Q2 - Queue 2 * Q3 - Queue 3 * EP1 - EventProcessor 1 * EP2 - EventProcessor 2 * EP3 - EventProcessor 3 * * * Disruptor: * ========== * track to prevent wrap * +--------------------+----------+----------+ * | | | | * | v v v * +----+ +====+ +====+ +-----+ +-----+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | | EP2 | | EP3 | * +----+ +====+ +====+ +-----+ +-----+ +-----+ * claim get ^ | | | * | | | | * +---------+----------+----------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * EP2 - EventProcessor 2 * EP3 - EventProcessor 3 * * </pre> */ public final class OnePublisherToThreeProcessorMultiCastThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int NUM_EVENT_PROCESSORS = 3; private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newFixedThreadPool(NUM_EVENT_PROCESSORS); private final long[] results = new long[NUM_EVENT_PROCESSORS]; { for (long i = 0; i < ITERATIONS; i++) { results[0] = Operation.ADDITION.op(results[0], i); results[1] = Operation.SUBTRACTION.op(results[1], i); results[2] = Operation.AND.op(results[2], i); } } /////////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("unchecked") private final BlockingQueue<Long>[] blockingQueues = new BlockingQueue[NUM_EVENT_PROCESSORS]; { blockingQueues[0] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); blockingQueues[1] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); blockingQueues[2] = new LinkedBlockingQueue<Long>(BUFFER_SIZE); } private final ValueMutationQueueProcessor[] queueProcessors = new ValueMutationQueueProcessor[NUM_EVENT_PROCESSORS]; { queueProcessors[0] = new ValueMutationQueueProcessor(blockingQueues[0], Operation.ADDITION, ITERATIONS - 1); queueProcessors[1] = new ValueMutationQueueProcessor(blockingQueues[1], Operation.SUBTRACTION, ITERATIONS - 1); queueProcessors[2] = new ValueMutationQueueProcessor(blockingQueues[2], Operation.AND, ITERATIONS - 1); } ///////////////////////////////////////////////////////////////////////////////////////////////
private final RingBuffer<ValueEvent> ringBuffer =
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/support/ValuePublisher.java
// Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // }
import com.lmax.disruptor.RingBuffer; import java.util.concurrent.CyclicBarrier;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class ValuePublisher implements Runnable { private final CyclicBarrier cyclicBarrier;
// Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // } // Path: src/performance/java/com/lmax/disruptor/support/ValuePublisher.java import com.lmax.disruptor.RingBuffer; import java.util.concurrent.CyclicBarrier; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class ValuePublisher implements Runnable { private final CyclicBarrier cyclicBarrier;
private final RingBuffer<ValueEvent> ringBuffer;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/support/TestWaiter.java
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // }
import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.RingBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class TestWaiter implements Callable<List<StubEvent>> { private final long toWaitForSequence; private final long initialSequence; private final CyclicBarrier cyclicBarrier;
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // } // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.RingBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class TestWaiter implements Callable<List<StubEvent>> { private final long toWaitForSequence; private final long initialSequence; private final CyclicBarrier cyclicBarrier;
private final SequenceBarrier sequenceBarrier;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/support/TestWaiter.java
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // }
import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.RingBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class TestWaiter implements Callable<List<StubEvent>> { private final long toWaitForSequence; private final long initialSequence; private final CyclicBarrier cyclicBarrier; private final SequenceBarrier sequenceBarrier;
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/RingBuffer.java // public final class RingBuffer<T> extends Sequencer // { // private final int indexMask; // private final Object[] entries; // // /** // * Construct a RingBuffer with the full option set. // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param claimStrategy threading strategy for publisher claiming entries in the ring. // * @param waitStrategy waiting strategy employed by processorsToTrack waiting on entries becoming available. // * // * @throws IllegalArgumentException if bufferSize is not a power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, // final ClaimStrategy claimStrategy, // final WaitStrategy waitStrategy) // { // super(claimStrategy, waitStrategy); // // if (Integer.bitCount(claimStrategy.getBufferSize()) != 1) // { // throw new IllegalArgumentException("bufferSize must be a power of 2"); // } // // indexMask = claimStrategy.getBufferSize() - 1; // entries = new Object[claimStrategy.getBufferSize()]; // // fill(eventFactory); // } // // /** // * Construct a RingBuffer with default strategies of: // * {@link MultiThreadedClaimStrategy} and {@link BlockingWaitStrategy} // * // * @param eventFactory to newInstance entries for filling the RingBuffer // * @param bufferSize of the RingBuffer that will be rounded up to the next power of 2 // */ // public RingBuffer(final EventFactory<T> eventFactory, final int bufferSize) // { // this(eventFactory, // new MultiThreadedClaimStrategy(bufferSize), // new BlockingWaitStrategy()); // } // // /** // * Get the event for a given sequence in the RingBuffer. // * // * @param sequence for the event // * @return event for the sequence // */ // @SuppressWarnings("unchecked") // public T get(final long sequence) // { // return (T)entries[(int)sequence & indexMask]; // } // // private void fill(final EventFactory<T> eventFactory) // { // for (int i = 0; i < entries.length; i++) // { // entries[i] = eventFactory.newInstance(); // } // } // } // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.RingBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.support; public final class TestWaiter implements Callable<List<StubEvent>> { private final long toWaitForSequence; private final long initialSequence; private final CyclicBarrier cyclicBarrier; private final SequenceBarrier sequenceBarrier;
private final RingBuffer<StubEvent> ringBuffer;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/SequencerTest.java
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // }
import com.lmax.disruptor.support.DaemonThreadFactory; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertFalse;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; public final class SequencerTest {
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // Path: src/test/java/com/lmax/disruptor/SequencerTest.java import com.lmax.disruptor.support.DaemonThreadFactory; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertFalse; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; public final class SequencerTest {
private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/SequenceReportingCallbackTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // }
import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; public class SequenceReportingCallbackTest { private final CountDownLatch callbackLatch = new CountDownLatch(1); private final CountDownLatch onEndOfBatchLatch = new CountDownLatch(1); @Test public void shouldReportProgressByUpdatingSequenceViaCallback() throws Exception {
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // Path: src/test/java/com/lmax/disruptor/SequenceReportingCallbackTest.java import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; public class SequenceReportingCallbackTest { private final CountDownLatch callbackLatch = new CountDownLatch(1); private final CountDownLatch onEndOfBatchLatch = new CountDownLatch(1); @Test public void shouldReportProgressByUpdatingSequenceViaCallback() throws Exception {
final RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 16);
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/BlockingWaitStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.lmax.disruptor.util.Util.getMinimumSequence;
private final Lock lock = new ReentrantLock(); private final Condition processorNotifyCondition = lock.newCondition(); private volatile int numWaiters = 0; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if ((availableSequence = cursor.get()) < sequence) { lock.lock(); try { ++numWaiters; while ((availableSequence = cursor.get()) < sequence) { barrier.checkAlert(); processorNotifyCondition.await(); } } finally { --numWaiters; lock.unlock(); } } if (0 != dependents.length) {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/BlockingWaitStrategy.java import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.lmax.disruptor.util.Util.getMinimumSequence; private final Lock lock = new ReentrantLock(); private final Condition processorNotifyCondition = lock.newCondition(); private volatile int numWaiters = 0; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if ((availableSequence = cursor.get()) < sequence) { lock.lock(); try { ++numWaiters; while ((availableSequence = cursor.get()) < sequence) { barrier.checkAlert(); processorNotifyCondition.await(); } } finally { --numWaiters; lock.unlock(); } } if (0 != dependents.length) {
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/SequenceGroup.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.util.Util; import java.util.concurrent.atomic.AtomicReference;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * {@link Sequence} group that can dynamically have {@link Sequence}s added and removed while being * thread safe. * <p> * The {@link SequenceGroup#get()} and {@link SequenceGroup#set(long)} methods are lock free and can be * concurrently be called with the {@link SequenceGroup#add(Sequence)} and {@link SequenceGroup#remove(Sequence)}. */ public final class SequenceGroup extends Sequence { private final AtomicReference<Sequence[]> sequencesRef = new AtomicReference<Sequence[]>(new Sequence[0]); /** * Default Constructor */ public SequenceGroup() { } /** * Get the minimum sequence value for the group. * * @return the minimum sequence value for the group. */ @Override public long get() {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/SequenceGroup.java import com.lmax.disruptor.util.Util; import java.util.concurrent.atomic.AtomicReference; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * {@link Sequence} group that can dynamically have {@link Sequence}s added and removed while being * thread safe. * <p> * The {@link SequenceGroup#get()} and {@link SequenceGroup#set(long)} methods are lock free and can be * concurrently be called with the {@link SequenceGroup#add(Sequence)} and {@link SequenceGroup#remove(Sequence)}. */ public final class SequenceGroup extends Sequence { private final AtomicReference<Sequence[]> sequencesRef = new AtomicReference<Sequence[]>(new Sequence[0]); /** * Default Constructor */ public SequenceGroup() { } /** * Get the minimum sequence value for the group. * * @return the minimum sequence value for the group. */ @Override public long get() {
return Util.getMinimumSequence(sequencesRef.get());
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/WorkerPool.java
// Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.util.PaddedAtomicLong; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * A pool of {@link WorkProcessor}s that will consume sequences so jobs can be farmed out across a pool of workers * which are implemented the {@link WorkHandler} interface. * * @param <T> event to be processed by a pool of workers */ public final class WorkerPool<T> { private final AtomicBoolean started = new AtomicBoolean(false);
// Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/WorkerPool.java import com.lmax.disruptor.util.PaddedAtomicLong; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor; /** * A pool of {@link WorkProcessor}s that will consume sequences so jobs can be farmed out across a pool of workers * which are implemented the {@link WorkHandler} interface. * * @param <T> event to be processed by a pool of workers */ public final class WorkerPool<T> { private final AtomicBoolean started = new AtomicBoolean(false);
private final PaddedAtomicLong workSequence = new PaddedAtomicLong(Sequencer.INITIAL_CURSOR_VALUE);
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/WorkerPool.java
// Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.util.PaddedAtomicLong; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean;
* * @param executor providing threads for running the workers. * @return the {@link RingBuffer} used for the work queue. * @throws IllegalStateException is the pool has already been started and not halted yet */ public RingBuffer<T> start(final Executor executor) { if (!started.compareAndSet(false, true)) { throw new IllegalStateException("WorkerPool has already been started and cannot be restarted until halted."); } final long cursor = ringBuffer.getCursor(); workSequence.set(cursor); for (WorkProcessor<?> processor : workProcessors) { processor.getSequence().set(cursor); executor.execute(processor); } return ringBuffer; } /** * Wait for the {@link RingBuffer} to drain of published events then halt the workers. */ public void drainAndHalt() { Sequence[] workerSequences = getWorkerSequences();
// Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/WorkerPool.java import com.lmax.disruptor.util.PaddedAtomicLong; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; * * @param executor providing threads for running the workers. * @return the {@link RingBuffer} used for the work queue. * @throws IllegalStateException is the pool has already been started and not halted yet */ public RingBuffer<T> start(final Executor executor) { if (!started.compareAndSet(false, true)) { throw new IllegalStateException("WorkerPool has already been started and cannot be restarted until halted."); } final long cursor = ringBuffer.getCursor(); workSequence.set(cursor); for (WorkProcessor<?> processor : workProcessors) { processor.getSequence().set(cursor); executor.execute(processor); } return ringBuffer; } /** * Wait for the {@link RingBuffer} to drain of published events then halt the workers. */ public void drainAndHalt() { Sequence[] workerSequences = getWorkerSequences();
while (ringBuffer.getCursor() > Util.getMinimumSequence(workerSequences))
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.dsl; /** * A group of {@link EventProcessor}s used as part of the {@link Disruptor}. * * @param <T> the type of entry used by the event processors. */ public class EventHandlerGroup<T> { private final Disruptor<T> disruptor; private final EventProcessorRepository<T> eventProcessorRepository;
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.dsl; /** * A group of {@link EventProcessor}s used as part of the {@link Disruptor}. * * @param <T> the type of entry used by the event processors. */ public class EventHandlerGroup<T> { private final Disruptor<T> disruptor; private final EventProcessorRepository<T> eventProcessorRepository;
private final EventProcessor[] eventProcessors;
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util;
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.dsl; /** * A group of {@link EventProcessor}s used as part of the {@link Disruptor}. * * @param <T> the type of entry used by the event processors. */ public class EventHandlerGroup<T> { private final Disruptor<T> disruptor; private final EventProcessorRepository<T> eventProcessorRepository; private final EventProcessor[] eventProcessors; EventHandlerGroup(final Disruptor<T> disruptor, final EventProcessorRepository<T> eventProcessorRepository, final EventProcessor[] eventProcessors) { this.disruptor = disruptor; this.eventProcessorRepository = eventProcessorRepository; this.eventProcessors = eventProcessors; } /** * Create a new event handler group that combines the handlers in this group with * <tt>handlers</tt>. * * @param handlers the handlers to combine. * @return a new EventHandlerGroup combining the existing and new handlers into a * single dependency group. */
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util; /* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.dsl; /** * A group of {@link EventProcessor}s used as part of the {@link Disruptor}. * * @param <T> the type of entry used by the event processors. */ public class EventHandlerGroup<T> { private final Disruptor<T> disruptor; private final EventProcessorRepository<T> eventProcessorRepository; private final EventProcessor[] eventProcessors; EventHandlerGroup(final Disruptor<T> disruptor, final EventProcessorRepository<T> eventProcessorRepository, final EventProcessor[] eventProcessors) { this.disruptor = disruptor; this.eventProcessorRepository = eventProcessorRepository; this.eventProcessors = eventProcessors; } /** * Create a new event handler group that combines the handlers in this group with * <tt>handlers</tt>. * * @param handlers the handlers to combine. * @return a new EventHandlerGroup combining the existing and new handlers into a * single dependency group. */
public EventHandlerGroup<T> and(final EventHandler<T>... handlers)