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
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // }
import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule {
@Provides static FactsPresenter presenter(GetRandomFacts usecase,
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // }
import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule {
@Provides static FactsPresenter presenter(GetRandomFacts usecase,
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // }
import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase,
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase,
DisplayFactsView view,
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // }
import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase, DisplayFactsView view,
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase, DisplayFactsView view,
BehavioursCoordinator coordinator,
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // }
import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase, DisplayFactsView view, BehavioursCoordinator coordinator,
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/BehavioursCoordinator.java // public class BehavioursCoordinator<T> implements FlowableTransformer<T, T> { // // private AssignEmptyState<T> dealWithEmptyState; // private AssignErrorState<T> assignErrorState; // private LoadingCoordination<T> loadingCoordinator; // private NetworkingErrorFeedback<T> networkingErrorFeedback; // private RefreshToogle<T> refreshToogle; // // public BehavioursCoordinator(AssignEmptyState<T> dealWithEmptyState, // AssignErrorState<T> assignErrorState, // LoadingCoordination<T> loadingCoordinator, // NetworkingErrorFeedback<T> networkingErrorFeedback, // RefreshToogle<T> refreshToogle) { // // this.dealWithEmptyState = dealWithEmptyState; // this.assignErrorState = assignErrorState; // this.loadingCoordinator = loadingCoordinator; // this.networkingErrorFeedback = networkingErrorFeedback; // this.refreshToogle = refreshToogle; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .compose(dealWithEmptyState) // .compose(assignErrorState) // .compose(loadingCoordinator) // .compose(refreshToogle) // .compose(networkingErrorFeedback); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/lifecycles/LifecycleStrategist.java // public class LifecycleStrategist { // // private DisposeStrategy strategy; // // public LifecycleStrategist(LifecycleOwner owner, DisposeStrategy strategy) { // this.strategy = strategy; // owner.getLifecycle().addObserver(strategy); // } // // public void applyStrategy(Disposable toDispose) { // strategy.addDisposable(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/GetRandomFacts.java // public interface GetRandomFacts { // // Flowable<FactAboutNumber> fetchTrivia(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsPresenter.java // public class FactsPresenter { // // private GetRandomFacts usecase; // private DisplayFactsView view; // private BehavioursCoordinator<FactAboutNumber> coordinator; // private LifecycleStrategist strategist; // private DomainToViewModel<FactAboutNumber, FactViewModel> mapper; // // public FactsPresenter(GetRandomFacts usecase, // DisplayFactsView view, // BehavioursCoordinator<FactAboutNumber> coordinator, // LifecycleStrategist strategist, // DomainToViewModel<FactAboutNumber, FactViewModel> mapper) { // // this.usecase = usecase; // this.view = view; // this.coordinator = coordinator; // this.strategist = strategist; // this.mapper = mapper; // } // // public void fetchRandomFacts() { // Flowable<FactViewModel> dataFlow = // usecase.fetchTrivia() // .compose(coordinator) // .map(fact -> mapper.translate(fact)); // // Disposable toDispose = view.subscribeInto(dataFlow); // strategist.applyStrategy(toDispose); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/PresentationModule.java import android.content.Context; import br.ufs.demos.rxmvp.playground.core.behaviours.BehavioursCoordinator; import br.ufs.demos.rxmvp.playground.core.lifecycles.LifecycleStrategist; import br.ufs.demos.rxmvp.playground.trivia.domain.GetRandomFacts; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsPresenter; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import dagger.Module; import dagger.Provides; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module(includes = InfrastructureModule.class) public class PresentationModule { @Provides static FactsPresenter presenter(GetRandomFacts usecase, DisplayFactsView view, BehavioursCoordinator coordinator,
LifecycleStrategist strategist,
ubiratansoares/reactive-architectures-playground
app/src/live/java/br/ufs/demos/rxmvp/playground/dagger/modules/RestWebServiceModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/webservice/NumbersWebService.java // public interface NumbersWebService { // // String BASE_URL = "http://numbersapi.com"; // // @GET("/{numbers}/trivia") Flowable<NumbersTriviaPayload> getTrivia( // @Path("numbers") String commaSeparatedNumbers // ); // // }
import br.ufs.demos.rxmvp.playground.webservice.NumbersWebService; import dagger.Module; import dagger.Provides; import dagger.Reusable; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module public class RestWebServiceModule {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/webservice/NumbersWebService.java // public interface NumbersWebService { // // String BASE_URL = "http://numbersapi.com"; // // @GET("/{numbers}/trivia") Flowable<NumbersTriviaPayload> getTrivia( // @Path("numbers") String commaSeparatedNumbers // ); // // } // Path: app/src/live/java/br/ufs/demos/rxmvp/playground/dagger/modules/RestWebServiceModule.java import br.ufs.demos.rxmvp.playground.webservice.NumbersWebService; import dagger.Module; import dagger.Provides; import dagger.Reusable; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 6/26/17. */ @Module public class RestWebServiceModule {
@Provides @Reusable static NumbersWebService webService(OkHttpClient customHttpClient) {
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/trivia/FactsViewModelMapperTests.java
// Path: app/src/mock/java/br/ufs/demos/rxmvp/playground/app/MainApplication.java // public class MainApplication extends Application implements HasActivityInjector { // // @Inject DispatchingAndroidInjector<Activity> injector; // @Inject public NumbersWebService webservice; // // @Override public void onCreate() { // super.onCreate(); // buildTopLevelDependenciesGraph(); // setupMock(); // } // // @Override public DispatchingAndroidInjector<Activity> activityInjector() { // return injector; // } // // protected void buildTopLevelDependenciesGraph() { // DaggerAppComponent.builder().application(this).build().inject(this); // } // // private void setupMock() { // FakeWebService service = (FakeWebService) webservice; // service.nextCallPerform(NextCall.SUCCESS_200); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/FactAboutNumber.java // public class FactAboutNumber { // // public String number; // public String fact; // // private FactAboutNumber(String number, String fact) { // this.number = number; // this.fact = fact; // } // // public static FactAboutNumber of(String number, String fact) { // return new FactAboutNumber(number, fact); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/ComposedWithSpannedStyles.java // public class ComposedWithSpannedStyles implements FactViewModel { // // private String number; // private String fact; // private ForegroundColorSpan numberColor; // // // private ComposedWithSpannedStyles(String number, // String fact, // ForegroundColorSpan numberColor) { // this.number = number; // this.fact = fact; // this.numberColor = numberColor; // } // // public static ComposedWithSpannedStyles with(String number, // String fact, // ForegroundColorSpan numberColor) { // // return new ComposedWithSpannedStyles(number, fact, numberColor); // } // // @Override public CharSequence formattedFact() { // // return new Spanny() // .append(number, new StyleSpan(Typeface.BOLD), numberColor) // .append(fact); // } // // @Override public int viewType() { // return TYPE_SINGLE_LABEL; // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/FactViewModel.java // public interface FactViewModel { // // int TYPE_TWO_LABELS = 0; // int TYPE_SINGLE_LABEL = 1; // // CharSequence formattedFact(); // // int viewType(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/NumberAndFact.java // public class NumberAndFact implements FactViewModel { // // private String number; // private String fact; // // public NumberAndFact(String number, String fact) { // this.number = number; // this.fact = fact; // } // // @Override public CharSequence formattedFact() { // return fact; // } // // @Override public int viewType() { // return TYPE_TWO_LABELS; // } // // public String relatedNumber() { // return number; // } // // }
import android.content.Context; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import br.ufs.demos.rxmvp.playground.BuildConfig; import br.ufs.demos.rxmvp.playground.app.MainApplication; import br.ufs.demos.rxmvp.playground.trivia.domain.FactAboutNumber; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.ComposedWithSpannedStyles; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.FactViewModel; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.NumberAndFact; import static org.assertj.core.api.Assertions.assertThat;
package br.ufs.demos.rxmvp.playground.trivia; /** * Created by bira on 7/8/17. */ @RunWith(RobolectricTestRunner.class) @Config( constants = BuildConfig.class,
// Path: app/src/mock/java/br/ufs/demos/rxmvp/playground/app/MainApplication.java // public class MainApplication extends Application implements HasActivityInjector { // // @Inject DispatchingAndroidInjector<Activity> injector; // @Inject public NumbersWebService webservice; // // @Override public void onCreate() { // super.onCreate(); // buildTopLevelDependenciesGraph(); // setupMock(); // } // // @Override public DispatchingAndroidInjector<Activity> activityInjector() { // return injector; // } // // protected void buildTopLevelDependenciesGraph() { // DaggerAppComponent.builder().application(this).build().inject(this); // } // // private void setupMock() { // FakeWebService service = (FakeWebService) webservice; // service.nextCallPerform(NextCall.SUCCESS_200); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/domain/FactAboutNumber.java // public class FactAboutNumber { // // public String number; // public String fact; // // private FactAboutNumber(String number, String fact) { // this.number = number; // this.fact = fact; // } // // public static FactAboutNumber of(String number, String fact) { // return new FactAboutNumber(number, fact); // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/FactsViewModelMapper.java // public class FactsViewModelMapper implements DomainToViewModel<FactAboutNumber, FactViewModel> { // // private static final int MAX_CHARS_FOR_SMALL_FACT = 50; // private Context context; // // public FactsViewModelMapper(Context context) { // this.context = context; // } // // @Override public FactViewModel translate(FactAboutNumber fact) { // if (isFactTooLarge(fact)) return composedWithSpans(fact); // return asNumberAndFact(fact); // } // // private FactViewModel asNumberAndFact(FactAboutNumber fact) { // return new NumberAndFact( // fact.number, // formatFact(fact.number, fact.fact) // ); // } // // private FactViewModel composedWithSpans(FactAboutNumber fact) { // // int accent = ContextCompat.getColor(context, R.color.colorAccent); // // return ComposedWithSpannedStyles.with( // fact.number, // " " + formatFact(fact.number, fact.fact), // new ForegroundColorSpan(accent) // ); // } // // private String formatFact(String number, String fact) { // return fact.replace(number + " ", ""); // } // // private boolean isFactTooLarge(FactAboutNumber fact) { // String formatted = formatFact(fact.number, fact.fact); // return formatted.length() > MAX_CHARS_FOR_SMALL_FACT; // } // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/ComposedWithSpannedStyles.java // public class ComposedWithSpannedStyles implements FactViewModel { // // private String number; // private String fact; // private ForegroundColorSpan numberColor; // // // private ComposedWithSpannedStyles(String number, // String fact, // ForegroundColorSpan numberColor) { // this.number = number; // this.fact = fact; // this.numberColor = numberColor; // } // // public static ComposedWithSpannedStyles with(String number, // String fact, // ForegroundColorSpan numberColor) { // // return new ComposedWithSpannedStyles(number, fact, numberColor); // } // // @Override public CharSequence formattedFact() { // // return new Spanny() // .append(number, new StyleSpan(Typeface.BOLD), numberColor) // .append(fact); // } // // @Override public int viewType() { // return TYPE_SINGLE_LABEL; // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/FactViewModel.java // public interface FactViewModel { // // int TYPE_TWO_LABELS = 0; // int TYPE_SINGLE_LABEL = 1; // // CharSequence formattedFact(); // // int viewType(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/NumberAndFact.java // public class NumberAndFact implements FactViewModel { // // private String number; // private String fact; // // public NumberAndFact(String number, String fact) { // this.number = number; // this.fact = fact; // } // // @Override public CharSequence formattedFact() { // return fact; // } // // @Override public int viewType() { // return TYPE_TWO_LABELS; // } // // public String relatedNumber() { // return number; // } // // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/trivia/FactsViewModelMapperTests.java import android.content.Context; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import br.ufs.demos.rxmvp.playground.BuildConfig; import br.ufs.demos.rxmvp.playground.app.MainApplication; import br.ufs.demos.rxmvp.playground.trivia.domain.FactAboutNumber; import br.ufs.demos.rxmvp.playground.trivia.presentation.FactsViewModelMapper; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.ComposedWithSpannedStyles; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.FactViewModel; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.NumberAndFact; import static org.assertj.core.api.Assertions.assertThat; package br.ufs.demos.rxmvp.playground.trivia; /** * Created by bira on 7/8/17. */ @RunWith(RobolectricTestRunner.class) @Config( constants = BuildConfig.class,
application = MainApplication.class,
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // }
import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule {
@Binds abstract DisplayFactsView displayFactsView(FactsAboutNumbersActivity activity);
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // }
import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule {
@Binds abstract DisplayFactsView displayFactsView(FactsAboutNumbersActivity activity);
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // }
import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module;
package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule { @Binds abstract DisplayFactsView displayFactsView(FactsAboutNumbersActivity activity);
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingView.java // public interface LoadingView { // // Action showLoading(); // // Action hideLoading(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorView.java // public interface NetworkingErrorView { // // Action reportNetworkingError(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/ToogleRefreshView.java // public interface ToogleRefreshView { // // Action disableRefresh(); // // Action enableRefresh(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/ui/FactsAboutNumbersActivity.java // public class FactsAboutNumbersActivity // extends AppCompatActivity implements DisplayFactsView { // // private static final String TAG = FactsAboutNumbersActivity.class.getSimpleName(); // // @BindView(R.id.recyclerview_facts) public RecyclerView factsView; // @BindView(R.id.container) View container; // @BindView(R.id.label_feedback_message) TextView feedbackMessage; // @BindView(R.id.progressBar) ProgressBar loading; // @BindView(R.id.fab) FloatingActionButton fab; // // @Inject FactsPresenter presenter; // // public FactsAdapter adapter; // // @Override protected void onCreate(Bundle savedInstanceState) { // AndroidInjection.inject(this); // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // setupViews(); // } // // @Override protected void onResume() { // super.onResume(); // newTrivia(); // } // // @Override public Action showLoading() { // return () -> loading.setVisibility(View.VISIBLE); // } // // @Override public Action hideLoading() { // return () -> loading.setVisibility(View.GONE); // } // // @Override public Action showEmptyState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_empty_state); // }; // } // // @Override public Action hideEmptyState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action showErrorState() { // return () -> { // feedbackMessage.setVisibility(View.VISIBLE); // feedbackMessage.setText(R.string.feedback_error_state); // }; // } // // @Override public Action hideErrorState() { // return () -> feedbackMessage.setVisibility(View.GONE); // } // // @Override public Action reportNetworkingError() { // return () -> // Snackbar.make(container, R.string.feedback_message_internet_issue, LENGTH_INDEFINITE) // .setAction("TENTAR NOVAMENTE", view -> newTrivia()) // .show(); // } // // @Override public Action disableRefresh() { // return () -> fab.setVisibility(View.GONE); // } // // @Override public Action enableRefresh() { // return () -> fab.setVisibility(View.VISIBLE); // } // // @Override public Disposable subscribeInto(Flowable<FactViewModel> flow) { // adapter.clear(); // return flow // .observeOn(AndroidSchedulers.mainThread()) // .subscribe( // model -> adapter.addModel(model), // throwable -> Log.e(TAG, "Error -> " + throwable.getMessage()), // () -> Log.i(TAG, "Done") // ); // } // // private void setupViews() { // fab.setOnClickListener(view -> newTrivia()); // adapter = new FactsAdapter(LayoutInflater.from(this)); // factsView.setLayoutManager(new LinearLayoutManager(this)); // factsView.setAdapter(adapter); // } // // private void newTrivia() { // if (presenter != null) presenter.fetchRandomFacts(); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/dagger/modules/FactsAboutNumbersModule.java import android.arch.lifecycle.LifecycleOwner; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent.LoadingView; import br.ufs.demos.rxmvp.playground.core.behaviours.networking.NetworkingErrorView; import br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh.ToogleRefreshView; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.ui.FactsAboutNumbersActivity; import dagger.Binds; import dagger.Module; package br.ufs.demos.rxmvp.playground.dagger.modules; /** * Created by bira on 7/5/17. */ @Module( includes = { BehavioursModule.class, LifecycleStrategistModule.class, PresentationModule.class } ) public abstract class FactsAboutNumbersModule { @Binds abstract DisplayFactsView displayFactsView(FactsAboutNumbersActivity activity);
@Binds abstract ToogleRefreshView toogleRefreshView(FactsAboutNumbersActivity activity);
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // }
import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; import io.reactivex.functions.Action;
package br.ufs.demos.rxmvp.playground.core.behaviours; /** * Created by bira on 6/30/17. */ public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { private Action whenStart; private Action atError;
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; import io.reactivex.functions.Action; package br.ufs.demos.rxmvp.playground.core.behaviours; /** * Created by bira on 6/30/17. */ public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { private Action whenStart; private Action atError;
private ErrorPredicate errorPredicate;
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorHandler.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/NetworkingError.java // public class NetworkingError extends RuntimeException { // // public NetworkingError(String message) { // super(message); // } // // }
import org.reactivestreams.Publisher; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.NetworkingError; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer;
package br.ufs.demos.rxmvp.playground.core.behaviours.networking; /** * Created by bira on 7/5/17. * <p> * A handler for infrastructure that checks for any networking * related errors and translates it to a proper mapped error * with better semantics */ public class NetworkingErrorHandler<T> implements FlowableTransformer<T, T> { @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream.onErrorResumeNext(this::handleIfNetworkingError); } private Publisher<T> handleIfNetworkingError(Throwable throwable) { if (isNetworkingError(throwable)) return asNetworkingError(throwable); return Flowable.error(throwable); } private Flowable<T> asNetworkingError(Throwable throwable) { String failure = failureFrom(throwable);
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/NetworkingError.java // public class NetworkingError extends RuntimeException { // // public NetworkingError(String message) { // super(message); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/networking/NetworkingErrorHandler.java import org.reactivestreams.Publisher; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.NetworkingError; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; package br.ufs.demos.rxmvp.playground.core.behaviours.networking; /** * Created by bira on 7/5/17. * <p> * A handler for infrastructure that checks for any networking * related errors and translates it to a proper mapped error * with better semantics */ public class NetworkingErrorHandler<T> implements FlowableTransformer<T, T> { @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream.onErrorResumeNext(this::handleIfNetworkingError); } private Publisher<T> handleIfNetworkingError(Throwable throwable) { if (isNetworkingError(throwable)) return asNetworkingError(throwable); return Flowable.error(throwable); } private Flowable<T> asNetworkingError(Throwable throwable) { String failure = failureFrom(throwable);
return Flowable.error(new NetworkingError(failure));
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingCoordination.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // }
import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler;
package br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent; /** * Created by bira on 6/29/17. */ public class LoadingCoordination<T> implements FlowableTransformer<T, T> { private LoadingView view; private Scheduler uiScheduler; public LoadingCoordination(LoadingView view, Scheduler uiScheduler) { this.view = view; this.uiScheduler = uiScheduler; } @Override public Publisher<T> apply(Flowable<T> upstream) {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/loadingcontent/LoadingCoordination.java import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; package br.ufs.demos.rxmvp.playground.core.behaviours.loadingcontent; /** * Created by bira on 6/29/17. */ public class LoadingCoordination<T> implements FlowableTransformer<T, T> { private LoadingView view; private Scheduler uiScheduler; public LoadingCoordination(LoadingView view, Scheduler uiScheduler) { this.view = view; this.uiScheduler = uiScheduler; } @Override public Publisher<T> apply(Flowable<T> upstream) {
ShowAtStartHideWhenDone<T> delegate = new ShowAtStartHideWhenDone<>(
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/ShowAtStartHideWhenDoneTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class ShowAtStartHideWhenDoneTests { Scheduler targetScheduler = Schedulers.trampoline(); @Mock Action whenStart; @Mock Action whenDone; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("AB", "CD")
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/ShowAtStartHideWhenDoneTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class ShowAtStartHideWhenDoneTests { Scheduler targetScheduler = Schedulers.trampoline(); @Mock Action whenStart; @Mock Action whenDone; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("AB", "CD")
.compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler))
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/ShowAtStartHideWhenDoneTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify;
@Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("AB", "CD") .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe(); verifyShowAndHideWithFlow(); } @Test public void shouldHideAtStart_AndNotShowError_WithEmptyFlow() throws Exception { Flowable.empty() .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe(); verifyShowAndHideWithFlow(); } @Test public void shouldHideAtStart_AndNotShowError_WithErrorFlow() throws Exception { Flowable.error(new RuntimeException("Damn it!!!")) .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe( o -> {}, Throwable::printStackTrace, () -> {} ); verifyShowAndHideWithFlow(); } private void verifyShowAndHideWithFlow() throws Exception {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/ShowAtStartHideWhenDone.java // public class ShowAtStartHideWhenDone<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action whenDone; // private Scheduler targetScheduler; // // public ShowAtStartHideWhenDone(Action whenStart, // Action whenDone, // Scheduler targetScheduler) { // this.whenStart = whenStart; // this.whenDone = whenDone; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> show()) // .doOnTerminate(this::hide); // } // // private void show() { // subscribeAndFireAction(whenStart); // } // // private void hide() { // subscribeAndFireAction(whenDone); // } // // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/ShowAtStartHideWhenDoneTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.ShowAtStartHideWhenDone; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("AB", "CD") .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe(); verifyShowAndHideWithFlow(); } @Test public void shouldHideAtStart_AndNotShowError_WithEmptyFlow() throws Exception { Flowable.empty() .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe(); verifyShowAndHideWithFlow(); } @Test public void shouldHideAtStart_AndNotShowError_WithErrorFlow() throws Exception { Flowable.error(new RuntimeException("Damn it!!!")) .compose(new ShowAtStartHideWhenDone<>(whenStart, whenDone, targetScheduler)) .subscribe( o -> {}, Throwable::printStackTrace, () -> {} ); verifyShowAndHideWithFlow(); } private void verifyShowAndHideWithFlow() throws Exception {
verify(whenStart, oneTimeOnly()).run();
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/infrastructure/PayloadValidator.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/Checks.java // public static boolean notNullNotEmpty(Collection<?> objects) { // return objects != null && !objects.isEmpty(); // }
import static br.ufs.demos.rxmvp.playground.util.Checks.notNullNotEmpty;
package br.ufs.demos.rxmvp.playground.trivia.infrastructure; /** * Created by bira on 6/28/17. */ public class PayloadValidator { boolean accept(NumbersTriviaPayload payload) {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/Checks.java // public static boolean notNullNotEmpty(Collection<?> objects) { // return objects != null && !objects.isEmpty(); // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/infrastructure/PayloadValidator.java import static br.ufs.demos.rxmvp.playground.util.Checks.notNullNotEmpty; package br.ufs.demos.rxmvp.playground.trivia.infrastructure; /** * Created by bira on 6/28/17. */ public class PayloadValidator { boolean accept(NumbersTriviaPayload payload) {
return notNullNotEmpty(payload.entrySet());
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline();
ErrorPredicate positive = error -> true;
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline(); ErrorPredicate positive = error -> true; ErrorPredicate negative = error -> false; @Mock Action whenStart; @Mock Action atError; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B", "C")
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline(); ErrorPredicate positive = error -> true; ErrorPredicate negative = error -> false; @Mock Action whenStart; @Mock Action atError; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B", "C")
.compose(new HideAtStartShowAtError<>(whenStart, atError, positive, scheduler))
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline(); ErrorPredicate positive = error -> true; ErrorPredicate negative = error -> false; @Mock Action whenStart; @Mock Action atError; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B", "C") .compose(new HideAtStartShowAtError<>(whenStart, atError, positive, scheduler)) .subscribe();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/HideAtStartShowAtError.java // public class HideAtStartShowAtError<T> implements FlowableTransformer<T, T> { // // private Action whenStart; // private Action atError; // private ErrorPredicate errorPredicate; // private Scheduler targetScheduler; // // public HideAtStartShowAtError(Action whenStart, // Action atError, // ErrorPredicate errorPredicate, // Scheduler targetScheduler) { // // this.whenStart = whenStart; // this.atError = atError; // this.errorPredicate = errorPredicate; // this.targetScheduler = targetScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream // .doOnSubscribe(subscription -> hide()) // .doOnError(this::evaluateAndShowIfApplicable); // } // // private void evaluateAndShowIfApplicable(Throwable throwable) { // if (errorPredicate.evaluate(throwable)) { // subscribeAndFireAction(atError); // } // } // // private void hide() { // subscribeAndFireAction(whenStart); // } // // private void subscribeAndFireAction(Action toPerform) { // Completable.fromAction(toPerform) // .subscribeOn(targetScheduler) // .subscribe(); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/util/ErrorPredicate.java // public interface ErrorPredicate { // // boolean evaluate(Throwable error); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/HideAtStartShowAtErrorTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.HideAtStartShowAtError; import br.ufs.demos.rxmvp.playground.util.ErrorPredicate; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class HideAtStartShowAtErrorTests { Scheduler scheduler = Schedulers.trampoline(); ErrorPredicate positive = error -> true; ErrorPredicate negative = error -> false; @Mock Action whenStart; @Mock Action atError; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); } @Test public void shouldHideAtStart_AndNotShowError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B", "C") .compose(new HideAtStartShowAtError<>(whenStart, atError, positive, scheduler)) .subscribe();
verify(whenStart, oneTimeOnly()).run();
ubiratansoares/reactive-architectures-playground
app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/RefreshToogle.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/UnexpectedResponseError.java // public class UnexpectedResponseError extends RuntimeException { // // public UnexpectedResponseError(String message) { // super(message); // } // // }
import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.UnexpectedResponseError; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; import io.reactivex.functions.Action;
package br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh; /** * Created by bira on 7/8/17. */ public class RefreshToogle<T> implements FlowableTransformer<T, T> { private final ToogleRefreshView view; private Scheduler targetScheduler; public RefreshToogle(ToogleRefreshView view, Scheduler targetScheduler) { this.view = view; this.targetScheduler = targetScheduler; } @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream .doOnSubscribe(subscription -> fireAction(view.disableRefresh())) .doOnError(this::enableForSpecialErrorCase) .doOnComplete(() -> fireAction(view.enableRefresh())); } private void enableForSpecialErrorCase(Throwable throwable) {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/UnexpectedResponseError.java // public class UnexpectedResponseError extends RuntimeException { // // public UnexpectedResponseError(String message) { // super(message); // } // // } // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/tooglerefresh/RefreshToogle.java import org.reactivestreams.Publisher; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.UnexpectedResponseError; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; import io.reactivex.functions.Action; package br.ufs.demos.rxmvp.playground.core.behaviours.tooglerefresh; /** * Created by bira on 7/8/17. */ public class RefreshToogle<T> implements FlowableTransformer<T, T> { private final ToogleRefreshView view; private Scheduler targetScheduler; public RefreshToogle(ToogleRefreshView view, Scheduler targetScheduler) { this.view = view; this.targetScheduler = targetScheduler; } @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream .doOnSubscribe(subscription -> fireAction(view.disableRefresh())) .doOnError(this::enableForSpecialErrorCase) .doOnComplete(() -> fireAction(view.enableRefresh())); } private void enableForSpecialErrorCase(Throwable throwable) {
if (!(throwable instanceof UnexpectedResponseError)) fireAction(view.enableRefresh());
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline();
AssignEmptyState<Integer> assignEmptyness;
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignEmptyState<Integer> assignEmptyness; @Mock Action showEmtpyState; @Mock Action hideEmtpyState; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this);
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignEmptyState<Integer> assignEmptyness; @Mock Action showEmtpyState; @Mock Action hideEmtpyState; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this);
EmptyStateView view = new EmptyStateView() {
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignEmptyState<Integer> assignEmptyness; @Mock Action showEmtpyState; @Mock Action hideEmtpyState; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); EmptyStateView view = new EmptyStateView() { @Override public Action showEmptyState() { return showEmtpyState; } @Override public Action hideEmptyState() { return hideEmtpyState; } }; assignEmptyness = new AssignEmptyState<>(view, uiScheduler); } @Test public void shouldNotAssignEmpty_WhenFlowEmmits() throws Exception { Flowable.just(10, 20, 30) .compose(assignEmptyness) .subscribe();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ public class AssignEmptyStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignEmptyState<Integer> assignEmptyness; @Mock Action showEmtpyState; @Mock Action hideEmtpyState; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); EmptyStateView view = new EmptyStateView() { @Override public Action showEmptyState() { return showEmtpyState; } @Override public Action hideEmptyState() { return hideEmtpyState; } }; assignEmptyness = new AssignEmptyState<>(view, uiScheduler); } @Test public void shouldNotAssignEmpty_WhenFlowEmmits() throws Exception { Flowable.just(10, 20, 30) .compose(assignEmptyness) .subscribe();
verify(hideEmtpyState, oneTimeOnly()).run();
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
.compose(assignEmptyness) .subscribe(); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldNotAssignEmpty_WithEmptyFlow() throws Exception { Flowable<Integer> empty = Flowable.empty(); empty.compose(assignEmptyness).subscribe(); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldNotAssignEmpty_WithNotTargetError() throws Exception { Flowable<Integer> broken = Flowable.error(new RuntimeException("WTF!!")); broken.compose(assignEmptyness) .subscribe( some -> {}, Throwable::printStackTrace, () -> {} ); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldAssignEmpty_WithNoContentError() throws Exception {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/AssignEmptyState.java // public class AssignEmptyState<T> implements FlowableTransformer<T, T> { // // private EmptyStateView view; // private Scheduler uiScheduler; // // public AssignEmptyState(EmptyStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideEmptyState(), // view.showEmptyState(), // error -> error instanceof ContentNotFoundError, // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/emptystate/EmptyStateView.java // public interface EmptyStateView { // // Action showEmptyState(); // // Action hideEmptyState(); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/ContentNotFoundError.java // public class ContentNotFoundError extends RuntimeException { // // @Override public String getMessage() { // return "No content available"; // } // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignEmptyStateTests.java import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.AssignEmptyState; import br.ufs.demos.rxmvp.playground.core.behaviours.emptystate.EmptyStateView; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.ContentNotFoundError; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; .compose(assignEmptyness) .subscribe(); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldNotAssignEmpty_WithEmptyFlow() throws Exception { Flowable<Integer> empty = Flowable.empty(); empty.compose(assignEmptyness).subscribe(); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldNotAssignEmpty_WithNotTargetError() throws Exception { Flowable<Integer> broken = Flowable.error(new RuntimeException("WTF!!")); broken.compose(assignEmptyness) .subscribe( some -> {}, Throwable::printStackTrace, () -> {} ); verify(hideEmtpyState, oneTimeOnly()).run(); verify(showEmtpyState, never()).run(); } @Test public void shouldAssignEmpty_WithNoContentError() throws Exception {
Flowable<Integer> broken = Flowable.error(new ContentNotFoundError());
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/DeserializationIssuesHandlerTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/UnexpectedResponseError.java // public class UnexpectedResponseError extends RuntimeException { // // public UnexpectedResponseError(String message) { // super(message); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/infraerrors/DeserializationIssuesHandler.java // public class DeserializationIssuesHandler<T> implements FlowableTransformer<T, T> { // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream.onErrorResumeNext(this::handleErrorFromDeserializer); // } // // private Publisher<T> handleErrorFromDeserializer(Throwable throwable) { // // if (isDeserializationError(throwable)) { // return Flowable.error(new UnexpectedResponseError("Deserialization Error")); // } // // return Flowable.error(throwable); // } // // private boolean isDeserializationError(Throwable throwable) { // return throwable instanceof IllegalStateException // || throwable instanceof JsonIOException // || throwable instanceof JsonSyntaxException // || throwable instanceof JsonParseException; // } // }
import com.google.gson.JsonIOException; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import org.junit.Test; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.UnexpectedResponseError; import br.ufs.demos.rxmvp.playground.core.infraerrors.DeserializationIssuesHandler; import io.reactivex.Flowable;
} @Test public void shouldHandle_GsonThrowsSintaxException() { Flowable<String> broken = Flowable.error(new JsonSyntaxException("Json should not have comments")); broken.compose(handler) .test() .assertError(this::checkHandledAsDeserializationError); } @Test public void shouldHandle_GsonThrowsParseException() { Flowable<String> broken = Flowable.error(new JsonParseException("Failed to parse object")); broken.compose(handler) .test() .assertError(this::checkHandledAsDeserializationError); } @Test public void shouldNotHandle_OtherErros() { IllegalAccessError fuck = new IllegalAccessError("FUCK"); Flowable<String> broken = Flowable.error(fuck); broken.compose(handler) .test() .assertError(throwable -> throwable.equals(fuck)); } private boolean checkHandledAsDeserializationError(Throwable throwable) {
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errors/UnexpectedResponseError.java // public class UnexpectedResponseError extends RuntimeException { // // public UnexpectedResponseError(String message) { // super(message); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/infraerrors/DeserializationIssuesHandler.java // public class DeserializationIssuesHandler<T> implements FlowableTransformer<T, T> { // // @Override public Publisher<T> apply(Flowable<T> upstream) { // return upstream.onErrorResumeNext(this::handleErrorFromDeserializer); // } // // private Publisher<T> handleErrorFromDeserializer(Throwable throwable) { // // if (isDeserializationError(throwable)) { // return Flowable.error(new UnexpectedResponseError("Deserialization Error")); // } // // return Flowable.error(throwable); // } // // private boolean isDeserializationError(Throwable throwable) { // return throwable instanceof IllegalStateException // || throwable instanceof JsonIOException // || throwable instanceof JsonSyntaxException // || throwable instanceof JsonParseException; // } // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/DeserializationIssuesHandlerTests.java import com.google.gson.JsonIOException; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import org.junit.Test; import br.ufs.demos.rxmvp.playground.core.behaviours.errors.UnexpectedResponseError; import br.ufs.demos.rxmvp.playground.core.infraerrors.DeserializationIssuesHandler; import io.reactivex.Flowable; } @Test public void shouldHandle_GsonThrowsSintaxException() { Flowable<String> broken = Flowable.error(new JsonSyntaxException("Json should not have comments")); broken.compose(handler) .test() .assertError(this::checkHandledAsDeserializationError); } @Test public void shouldHandle_GsonThrowsParseException() { Flowable<String> broken = Flowable.error(new JsonParseException("Failed to parse object")); broken.compose(handler) .test() .assertError(this::checkHandledAsDeserializationError); } @Test public void shouldNotHandle_OtherErros() { IllegalAccessError fuck = new IllegalAccessError("FUCK"); Flowable<String> broken = Flowable.error(fuck); broken.compose(handler) .test() .assertError(throwable -> throwable.equals(fuck)); } private boolean checkHandledAsDeserializationError(Throwable throwable) {
if (throwable instanceof UnexpectedResponseError) {
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/trivia/FakeDisplayFactsView.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/FactViewModel.java // public interface FactViewModel { // // int TYPE_TWO_LABELS = 0; // int TYPE_SINGLE_LABEL = 1; // // CharSequence formattedFact(); // // int viewType(); // // }
import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.FactViewModel; import io.reactivex.Flowable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer;
package br.ufs.demos.rxmvp.playground.trivia; /** * Created by bira on 6/30/17. */ public class FakeDisplayFactsView implements DisplayFactsView { @Mock private Action showEmptyAction; @Mock private Action hideEmptyAction; @Mock private Action showErrorAction; @Mock private Action hideErrorAction; @Mock private Action showLoadingAction; @Mock private Action hideLoadingAction; @Mock private Action reportNetworkingErrorAction; @Mock private Action enableRefresh; @Mock private Action disableRefresh;
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/DisplayFactsView.java // public interface DisplayFactsView extends // LoadingView, // ErrorStateView, // EmptyStateView, // NetworkingErrorView, // ToogleRefreshView { // // Disposable subscribeInto(Flowable<FactViewModel> flow); // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/trivia/presentation/models/FactViewModel.java // public interface FactViewModel { // // int TYPE_TWO_LABELS = 0; // int TYPE_SINGLE_LABEL = 1; // // CharSequence formattedFact(); // // int viewType(); // // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/trivia/FakeDisplayFactsView.java import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.ufs.demos.rxmvp.playground.trivia.presentation.DisplayFactsView; import br.ufs.demos.rxmvp.playground.trivia.presentation.models.FactViewModel; import io.reactivex.Flowable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; package br.ufs.demos.rxmvp.playground.trivia; /** * Created by bira on 6/30/17. */ public class FakeDisplayFactsView implements DisplayFactsView { @Mock private Action showEmptyAction; @Mock private Action hideEmptyAction; @Mock private Action showErrorAction; @Mock private Action hideErrorAction; @Mock private Action showLoadingAction; @Mock private Action hideLoadingAction; @Mock private Action reportNetworkingErrorAction; @Mock private Action enableRefresh; @Mock private Action disableRefresh;
private Consumer<FactViewModel> modelConsumer;
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline();
AssignErrorState<String> assignErrorState;
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignErrorState<String> assignErrorState; @Mock Action show; @Mock Action hide; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this);
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignErrorState<String> assignErrorState; @Mock Action show; @Mock Action hide; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this);
ErrorStateView view = new ErrorStateView() {
ubiratansoares/reactive-architectures-playground
app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify;
package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignErrorState<String> assignErrorState; @Mock Action show; @Mock Action hide; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); ErrorStateView view = new ErrorStateView() { @Override public Action showErrorState() { return show; } @Override public Action hideErrorState() { return hide; } }; assignErrorState = new AssignErrorState<>(view, uiScheduler); } @Test public void shouldNotAssignError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B") .compose(assignErrorState) .subscribe();
// Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/AssignErrorState.java // public class AssignErrorState<T> implements FlowableTransformer<T, T> { // // private ErrorStateView view; // private Scheduler uiScheduler; // // public AssignErrorState(ErrorStateView view, Scheduler uiScheduler) { // this.view = view; // this.uiScheduler = uiScheduler; // } // // @Override public Publisher<T> apply(Flowable<T> upstream) { // HideAtStartShowAtError<T> delegate = new HideAtStartShowAtError<>( // view.hideErrorState(), // view.showErrorState(), // error -> !(error instanceof ContentNotFoundError), // uiScheduler // ); // // return upstream.compose(delegate); // } // // } // // Path: app/src/main/java/br/ufs/demos/rxmvp/playground/core/behaviours/errorstate/ErrorStateView.java // public interface ErrorStateView { // // Action showErrorState(); // // Action hideErrorState(); // // } // // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/util/MockitoHelpers.java // public static VerificationMode oneTimeOnly() { // return VerificationModeFactory.times(1); // } // Path: app/src/test/java/br/ufs/demos/rxmvp/playground/core/AssignErrorStateTests.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.AssignErrorState; import br.ufs.demos.rxmvp.playground.core.behaviours.errorstate.ErrorStateView; import io.reactivex.Flowable; import io.reactivex.Scheduler; import io.reactivex.functions.Action; import io.reactivex.schedulers.Schedulers; import static br.ufs.demos.rxmvp.playground.util.MockitoHelpers.oneTimeOnly; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; package br.ufs.demos.rxmvp.playground.core; /** * Created by bira on 6/30/17. */ @RunWith(MockitoJUnitRunner.class) public class AssignErrorStateTests { Scheduler uiScheduler = Schedulers.trampoline(); AssignErrorState<String> assignErrorState; @Mock Action show; @Mock Action hide; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); ErrorStateView view = new ErrorStateView() { @Override public Action showErrorState() { return show; } @Override public Action hideErrorState() { return hide; } }; assignErrorState = new AssignErrorState<>(view, uiScheduler); } @Test public void shouldNotAssignError_WhenFlowEmmits() throws Exception { Flowable.just("A", "B") .compose(assignErrorState) .subscribe();
verify(hide, oneTimeOnly()).run();
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> Constructor<T> noArgsConstructor(Class<T> beanClass) { // try { // return beanClass.getDeclaredConstructor(); // } catch (NoSuchMethodException exception) { // throw new BeanMatchersException("Bean does not have no-args constructor", exception); // } // }
import static com.google.code.beanmatchers.BeanOperations.noArgsConstructor; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher;
package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcher extends TypeSafeDiagnosingMatcher<Class> { @Override protected boolean matchesSafely(Class item, Description mismatchDescription) { try {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> Constructor<T> noArgsConstructor(Class<T> beanClass) { // try { // return beanClass.getDeclaredConstructor(); // } catch (NoSuchMethodException exception) { // throw new BeanMatchersException("Bean does not have no-args constructor", exception); // } // } // Path: src/main/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcher.java import static com.google.code.beanmatchers.BeanOperations.noArgsConstructor; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcher extends TypeSafeDiagnosingMatcher<Class> { @Override protected boolean matchesSafely(Class item, Description mismatchDescription) { try {
noArgsConstructor(item);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/JavaBeanTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithIntegerProperty.java // public class TestBeanWithIntegerProperty { // // private Integer integerProperty; // // public Integer getIntegerProperty() { // return integerProperty; // } // // public void setIntegerProperty(Integer integerProperty) { // this.integerProperty = integerProperty; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import com.google.code.beanmatchers.data.TestBeanWithIntegerProperty; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import java.util.List; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class JavaBeanTest { private JavaBean unitUnderTest; @Test public void canObtainBeanType() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithIntegerProperty.java // public class TestBeanWithIntegerProperty { // // private Integer integerProperty; // // public Integer getIntegerProperty() { // return integerProperty; // } // // public void setIntegerProperty(Integer integerProperty) { // this.integerProperty = integerProperty; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // Path: src/test/java/com/google/code/beanmatchers/JavaBeanTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import com.google.code.beanmatchers.data.TestBeanWithIntegerProperty; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import java.util.List; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class JavaBeanTest { private JavaBean unitUnderTest; @Test public void canObtainBeanType() { // given
TestBeanWithIntegerProperty bean = new TestBeanWithIntegerProperty();
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/JavaBeanTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithIntegerProperty.java // public class TestBeanWithIntegerProperty { // // private Integer integerProperty; // // public Integer getIntegerProperty() { // return integerProperty; // } // // public void setIntegerProperty(Integer integerProperty) { // this.integerProperty = integerProperty; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import com.google.code.beanmatchers.data.TestBeanWithIntegerProperty; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import java.util.List; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class JavaBeanTest { private JavaBean unitUnderTest; @Test public void canObtainBeanType() { // given TestBeanWithIntegerProperty bean = new TestBeanWithIntegerProperty(); Class expectedType = TestBeanWithIntegerProperty.class; unitUnderTest = new JavaBean(bean); // when Class type = unitUnderTest.beanType(); // then assertThat(type, is(equalTo(expectedType))); } @Test public void canObtainPropertyType() { // given TestBeanWithIntegerProperty bean = new TestBeanWithIntegerProperty(); Class expectedType = Integer.class; unitUnderTest = new JavaBean(bean); // when Class type = unitUnderTest.propertyType("integerProperty"); // then assertThat(type, is(equalTo(expectedType))); } @Test(expectedExceptions = BeanMatchersException.class) public void propertyTypeShouldThrowExceptionGivenPropertyDoesNotExistOnBean() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithIntegerProperty.java // public class TestBeanWithIntegerProperty { // // private Integer integerProperty; // // public Integer getIntegerProperty() { // return integerProperty; // } // // public void setIntegerProperty(Integer integerProperty) { // this.integerProperty = integerProperty; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // Path: src/test/java/com/google/code/beanmatchers/JavaBeanTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import com.google.code.beanmatchers.data.TestBeanWithIntegerProperty; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import java.util.List; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class JavaBeanTest { private JavaBean unitUnderTest; @Test public void canObtainBeanType() { // given TestBeanWithIntegerProperty bean = new TestBeanWithIntegerProperty(); Class expectedType = TestBeanWithIntegerProperty.class; unitUnderTest = new JavaBean(bean); // when Class type = unitUnderTest.beanType(); // then assertThat(type, is(equalTo(expectedType))); } @Test public void canObtainPropertyType() { // given TestBeanWithIntegerProperty bean = new TestBeanWithIntegerProperty(); Class expectedType = Integer.class; unitUnderTest = new JavaBean(bean); // when Class type = unitUnderTest.propertyType("integerProperty"); // then assertThat(type, is(equalTo(expectedType))); } @Test(expectedExceptions = BeanMatchersException.class) public void propertyTypeShouldThrowExceptionGivenPropertyDoesNotExistOnBean() { // given
TestBeanWithOneProperty bean = new TestBeanWithOneProperty();
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeExcludingMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // }
import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanHashCodeExcludingMatcherTest { private HasValidBeanHashCodeExcludingMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeExcludingMatcherTest.java import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanHashCodeExcludingMatcherTest { private HasValidBeanHashCodeExcludingMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given
Class beanType = TestBeanWithOneProperty.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeExcludingMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // }
import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanHashCodeExcludingMatcherTest { private HasValidBeanHashCodeExcludingMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; unitUnderTest = new HasValidBeanHashCodeExcludingMatcher(valueGeneratorMock); // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithPropertyNotInfluencingHashCodeShouldNotMatch() { // given unitUnderTest = new HasValidBeanHashCodeExcludingMatcher(valueGeneratorMock);
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeExcludingMatcherTest.java import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanHashCodeExcludingMatcherTest { private HasValidBeanHashCodeExcludingMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; unitUnderTest = new HasValidBeanHashCodeExcludingMatcher(valueGeneratorMock); // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithPropertyNotInfluencingHashCodeShouldNotMatch() { // given unitUnderTest = new HasValidBeanHashCodeExcludingMatcher(valueGeneratorMock);
Class beanType = TestBeanWithPropertyThatDoesNotInfluenceHashCode.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanMatchersTest.java
// Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanConstructor() { // return new HasValidBeanConstructorMatcher(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEquals() { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsExcluding(String... properties) { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsFor(String... properties) { // return new HasValidBeanEqualsForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCode() { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeExcluding(String... properties) { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeFor(String... properties) { // return new HasValidBeanHashCodeForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToString() { // return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringExcluding(String... properties) { // return new HasToStringDescribingPropertiesExcludingMatcher( // TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringFor(String... properties) { // return new HasToStringDescribingPropertiesMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSetters() { // return hasValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersExcluding(String... properties) { // return new InstantiatingMatcherDecorator( // isABeanWithValidGettersAndSettersExcluding(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersFor(String... properties) { // return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersFor(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSetters() { // return isABeanWithValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersExcluding(String... properties) { // return new HasValidGettersAndSettersExcludingMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersFor(String... properties) { // return new HasValidGettersAndSettersMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // }
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCode; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToString; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersFor; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersFor; import static org.hamcrest.MatcherAssert.assertThat; import com.google.code.beanmatchers.data.*; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class BeanMatchersTest { @Test public void testHasValidBeanConstructor() {
// Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanConstructor() { // return new HasValidBeanConstructorMatcher(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEquals() { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsExcluding(String... properties) { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsFor(String... properties) { // return new HasValidBeanEqualsForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCode() { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeExcluding(String... properties) { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeFor(String... properties) { // return new HasValidBeanHashCodeForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToString() { // return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringExcluding(String... properties) { // return new HasToStringDescribingPropertiesExcludingMatcher( // TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringFor(String... properties) { // return new HasToStringDescribingPropertiesMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSetters() { // return hasValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersExcluding(String... properties) { // return new InstantiatingMatcherDecorator( // isABeanWithValidGettersAndSettersExcluding(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersFor(String... properties) { // return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersFor(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSetters() { // return isABeanWithValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersExcluding(String... properties) { // return new HasValidGettersAndSettersExcludingMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersFor(String... properties) { // return new HasValidGettersAndSettersMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // Path: src/test/java/com/google/code/beanmatchers/BeanMatchersTest.java import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCode; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToString; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersFor; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersFor; import static org.hamcrest.MatcherAssert.assertThat; import com.google.code.beanmatchers.data.*; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class BeanMatchersTest { @Test public void testHasValidBeanConstructor() {
assertThat(TestBeanWithOneProperty.class, hasValidBeanConstructor());
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanMatchersTest.java
// Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanConstructor() { // return new HasValidBeanConstructorMatcher(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEquals() { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsExcluding(String... properties) { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsFor(String... properties) { // return new HasValidBeanEqualsForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCode() { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeExcluding(String... properties) { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeFor(String... properties) { // return new HasValidBeanHashCodeForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToString() { // return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringExcluding(String... properties) { // return new HasToStringDescribingPropertiesExcludingMatcher( // TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringFor(String... properties) { // return new HasToStringDescribingPropertiesMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSetters() { // return hasValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersExcluding(String... properties) { // return new InstantiatingMatcherDecorator( // isABeanWithValidGettersAndSettersExcluding(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersFor(String... properties) { // return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersFor(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSetters() { // return isABeanWithValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersExcluding(String... properties) { // return new HasValidGettersAndSettersExcludingMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersFor(String... properties) { // return new HasValidGettersAndSettersMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // }
import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCode; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToString; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersFor; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersFor; import static org.hamcrest.MatcherAssert.assertThat; import com.google.code.beanmatchers.data.*; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class BeanMatchersTest { @Test public void testHasValidBeanConstructor() { assertThat(TestBeanWithOneProperty.class, hasValidBeanConstructor()); } @Test public void testBeanHasValidGettersAndSettersFor() {
// Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanConstructor() { // return new HasValidBeanConstructorMatcher(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEquals() { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsExcluding(String... properties) { // return new HasValidBeanEqualsExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanEqualsFor(String... properties) { // return new HasValidBeanEqualsForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCode() { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeExcluding(String... properties) { // return new HasValidBeanHashCodeExcludingMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanHashCodeFor(String... properties) { // return new HasValidBeanHashCodeForMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToString() { // return new HasToStringDescribingPropertiesExcludingMatcher(TYPE_BASED_VALUE_GENERATOR); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringExcluding(String... properties) { // return new HasToStringDescribingPropertiesExcludingMatcher( // TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidBeanToStringFor(String... properties) { // return new HasToStringDescribingPropertiesMatcher(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSetters() { // return hasValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersExcluding(String... properties) { // return new InstantiatingMatcherDecorator( // isABeanWithValidGettersAndSettersExcluding(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static Matcher<Class> hasValidGettersAndSettersFor(String... properties) { // return new InstantiatingMatcherDecorator(isABeanWithValidGettersAndSettersFor(properties)); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSetters() { // return isABeanWithValidGettersAndSettersExcluding(); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersExcluding(String... properties) { // return new HasValidGettersAndSettersExcludingMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanMatchers.java // public static <T> Matcher<T> isABeanWithValidGettersAndSettersFor(String... properties) { // return new HasValidGettersAndSettersMatcher<T>(TYPE_BASED_VALUE_GENERATOR, properties); // } // Path: src/test/java/com/google/code/beanmatchers/BeanMatchersTest.java import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEquals; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCode; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToString; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringFor; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersFor; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSetters; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersExcluding; import static com.google.code.beanmatchers.BeanMatchers.isABeanWithValidGettersAndSettersFor; import static org.hamcrest.MatcherAssert.assertThat; import com.google.code.beanmatchers.data.*; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class BeanMatchersTest { @Test public void testHasValidBeanConstructor() { assertThat(TestBeanWithOneProperty.class, hasValidBeanConstructor()); } @Test public void testBeanHasValidGettersAndSettersFor() {
assertThat(new TestBeanWithOneProperty(), isABeanWithValidGettersAndSettersFor("field1"));
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/ValueGeneratorsTest.java
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // }
import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class ValueGeneratorsTest { @Mock private TypeBasedValueGenerator valueGeneratorMock; @BeforeMethod public void setUp() { initMocks(this); } @Test public void canGenerateTwoValues() { // given when(valueGeneratorMock.generate(Integer.class)).thenReturn(1, 2); // when
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // } // Path: src/test/java/com/google/code/beanmatchers/ValueGeneratorsTest.java import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class ValueGeneratorsTest { @Mock private TypeBasedValueGenerator valueGeneratorMock; @BeforeMethod public void setUp() { initMocks(this); } @Test public void canGenerateTwoValues() { // given when(valueGeneratorMock.generate(Integer.class)).thenReturn(1, 2); // when
DistinctValues<Integer> result = generateTwoDistinctValues(valueGeneratorMock, Integer.class);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/EnumBasedValueGeneratorTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // } // // Path: src/test/java/com/google/code/beanmatchers/data/EnumWithThreeValues.java // public enum EnumWithThreeValues { // VALUE_ONE, VALUE_TWO, VALUE_THREE // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import com.google.code.beanmatchers.data.EnumWithThreeValues; import java.util.Random; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class EnumBasedValueGeneratorTest { private EnumBasedValueGenerator unitUnderTest; @Mock private Random randomMock; @BeforeMethod public void setUp() { initMocks(this); unitUnderTest = new EnumBasedValueGenerator(randomMock); } @Test public void shouldObtainEnumValue() { // when
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // } // // Path: src/test/java/com/google/code/beanmatchers/data/EnumWithThreeValues.java // public enum EnumWithThreeValues { // VALUE_ONE, VALUE_TWO, VALUE_THREE // } // Path: src/test/java/com/google/code/beanmatchers/EnumBasedValueGeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import com.google.code.beanmatchers.data.EnumWithThreeValues; import java.util.Random; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class EnumBasedValueGeneratorTest { private EnumBasedValueGenerator unitUnderTest; @Mock private Random randomMock; @BeforeMethod public void setUp() { initMocks(this); unitUnderTest = new EnumBasedValueGenerator(randomMock); } @Test public void shouldObtainEnumValue() { // when
EnumWithOneValue value = unitUnderTest.generate(EnumWithOneValue.class);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/EnumBasedValueGeneratorTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // } // // Path: src/test/java/com/google/code/beanmatchers/data/EnumWithThreeValues.java // public enum EnumWithThreeValues { // VALUE_ONE, VALUE_TWO, VALUE_THREE // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import com.google.code.beanmatchers.data.EnumWithThreeValues; import java.util.Random; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class EnumBasedValueGeneratorTest { private EnumBasedValueGenerator unitUnderTest; @Mock private Random randomMock; @BeforeMethod public void setUp() { initMocks(this); unitUnderTest = new EnumBasedValueGenerator(randomMock); } @Test public void shouldObtainEnumValue() { // when EnumWithOneValue value = unitUnderTest.generate(EnumWithOneValue.class); // then assertThat(value, is(EnumWithOneValue.ONE_VALUE)); } @Test public void shouldObtainRandomEnumValue() { // given when(randomMock.nextInt(3)).thenReturn(2); // when
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // } // // Path: src/test/java/com/google/code/beanmatchers/data/EnumWithThreeValues.java // public enum EnumWithThreeValues { // VALUE_ONE, VALUE_TWO, VALUE_THREE // } // Path: src/test/java/com/google/code/beanmatchers/EnumBasedValueGeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import com.google.code.beanmatchers.data.EnumWithThreeValues; import java.util.Random; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class EnumBasedValueGeneratorTest { private EnumBasedValueGenerator unitUnderTest; @Mock private Random randomMock; @BeforeMethod public void setUp() { initMocks(this); unitUnderTest = new EnumBasedValueGenerator(randomMock); } @Test public void shouldObtainEnumValue() { // when EnumWithOneValue value = unitUnderTest.generate(EnumWithOneValue.class); // then assertThat(value, is(EnumWithOneValue.ONE_VALUE)); } @Test public void shouldObtainRandomEnumValue() { // given when(randomMock.nextInt(3)).thenReturn(2); // when
EnumWithThreeValues value = unitUnderTest.generate(EnumWithThreeValues.class);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/InstantiatingMatcherDecoratorTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class InstantiatingMatcherDecoratorTest { private InstantiatingMatcherDecorator unitUnderTest; @Mock private Matcher matcherMock; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); } @Test public void shouldInstantiateBeanAndDelegate() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // Path: src/test/java/com/google/code/beanmatchers/InstantiatingMatcherDecoratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class InstantiatingMatcherDecoratorTest { private InstantiatingMatcherDecorator unitUnderTest; @Mock private Matcher matcherMock; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); } @Test public void shouldInstantiateBeanAndDelegate() { // given
Class beanType = TestBeanWithOneProperty.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/DefaultTypeBasedValueGeneratorTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import java.io.File; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
File expectedValue = new File("."); when(valueGeneratorRepositoryMock.retrieveValueGenerator(File.class)).thenReturn(null); when(nonFinalTypeBasedValueGeneratorMock.generate(File.class)).thenReturn(expectedValue); // when File value = unitUnderTest.generate(File.class); // then assertThat(value, is(expectedValue)); } @Test(expectedExceptions = BeanMatchersException.class, expectedExceptionsMessageRegExp = "Could not create a test value of type java.lang.String.\\n" + "Please register a ValueGenerator to create the value:\\n" + " BeanMatchers.registerValueGenerator\\(new ValueGenerator<String>\\(\\) \\{\\n" + " public String generate\\(\\) \\{\\n" + " return null; // Change to generate random instance\\n" + " }\\n" + " \\}, String.class\\);") public void shouldThrowExceptionWhenNoGeneratorRegisteredForTypeAndTypeIsFinal() { // given when(valueGeneratorRepositoryMock.retrieveValueGenerator(String.class)).thenReturn(null); // when unitUnderTest.generate(String.class); } @Test public void shouldUseEnumGeneratorGivenTypeIsEnum() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/EnumWithOneValue.java // public enum EnumWithOneValue { // ONE_VALUE // } // Path: src/test/java/com/google/code/beanmatchers/DefaultTypeBasedValueGeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.EnumWithOneValue; import java.io.File; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; File expectedValue = new File("."); when(valueGeneratorRepositoryMock.retrieveValueGenerator(File.class)).thenReturn(null); when(nonFinalTypeBasedValueGeneratorMock.generate(File.class)).thenReturn(expectedValue); // when File value = unitUnderTest.generate(File.class); // then assertThat(value, is(expectedValue)); } @Test(expectedExceptions = BeanMatchersException.class, expectedExceptionsMessageRegExp = "Could not create a test value of type java.lang.String.\\n" + "Please register a ValueGenerator to create the value:\\n" + " BeanMatchers.registerValueGenerator\\(new ValueGenerator<String>\\(\\) \\{\\n" + " public String generate\\(\\) \\{\\n" + " return null; // Change to generate random instance\\n" + " }\\n" + " \\}, String.class\\);") public void shouldThrowExceptionWhenNoGeneratorRegisteredForTypeAndTypeIsFinal() { // given when(valueGeneratorRepositoryMock.retrieveValueGenerator(String.class)).thenReturn(null); // when unitUnderTest.generate(String.class); } @Test public void shouldUseEnumGeneratorGivenTypeIsEnum() { // given
EnumWithOneValue expectedValue = EnumWithOneValue.ONE_VALUE;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithoutNoArgsConstructor.java // public class TestBeanWithoutNoArgsConstructor { // // private boolean booleanProperty; // // public TestBeanWithoutNoArgsConstructor(boolean booleanProperty) { // } // // public boolean isBooleanProperty() { // return booleanProperty; // } // // public void setBooleanProperty(boolean booleanProperty) { // this.booleanProperty = booleanProperty; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithoutNoArgsConstructor; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcherTest { private HasValidBeanConstructorMatcher unitUnderTest; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { unitUnderTest = new HasValidBeanConstructorMatcher(); initMocks(this); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithNoArgsConstructorShouldMatch() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithoutNoArgsConstructor.java // public class TestBeanWithoutNoArgsConstructor { // // private boolean booleanProperty; // // public TestBeanWithoutNoArgsConstructor(boolean booleanProperty) { // } // // public boolean isBooleanProperty() { // return booleanProperty; // } // // public void setBooleanProperty(boolean booleanProperty) { // this.booleanProperty = booleanProperty; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcherTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithoutNoArgsConstructor; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcherTest { private HasValidBeanConstructorMatcher unitUnderTest; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { unitUnderTest = new HasValidBeanConstructorMatcher(); initMocks(this); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithNoArgsConstructorShouldMatch() { // given
Class beanType = TestBeanWithOneProperty.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithoutNoArgsConstructor.java // public class TestBeanWithoutNoArgsConstructor { // // private boolean booleanProperty; // // public TestBeanWithoutNoArgsConstructor(boolean booleanProperty) { // } // // public boolean isBooleanProperty() { // return booleanProperty; // } // // public void setBooleanProperty(boolean booleanProperty) { // this.booleanProperty = booleanProperty; // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithoutNoArgsConstructor; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcherTest { private HasValidBeanConstructorMatcher unitUnderTest; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { unitUnderTest = new HasValidBeanConstructorMatcher(); initMocks(this); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithNoArgsConstructorShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithoutNoArgsConstructorShouldNotMatch() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithoutNoArgsConstructor.java // public class TestBeanWithoutNoArgsConstructor { // // private boolean booleanProperty; // // public TestBeanWithoutNoArgsConstructor(boolean booleanProperty) { // } // // public boolean isBooleanProperty() { // return booleanProperty; // } // // public void setBooleanProperty(boolean booleanProperty) { // this.booleanProperty = booleanProperty; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanConstructorMatcherTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithoutNoArgsConstructor; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanConstructorMatcherTest { private HasValidBeanConstructorMatcher unitUnderTest; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { unitUnderTest = new HasValidBeanConstructorMatcher(); initMocks(this); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithNoArgsConstructorShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithoutNoArgsConstructorShouldNotMatch() { // given
Class beanType = TestBeanWithoutNoArgsConstructor.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeForMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // }
import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanHashCodeForMatcherTest { private HasValidBeanHashCodeForMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo, valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeForMatcherTest.java import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanHashCodeForMatcherTest { private HasValidBeanHashCodeForMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo, valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given
Class beanType = TestBeanWithOneProperty.class;
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeForMatcherTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // }
import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class HasValidBeanHashCodeForMatcherTest { private HasValidBeanHashCodeForMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo, valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; unitUnderTest = new HasValidBeanHashCodeForMatcher(valueGeneratorMock, "field1"); // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithPropertyNotInfluencingHashCodeShouldNotMatch() { // given unitUnderTest = new HasValidBeanHashCodeForMatcher(valueGeneratorMock, "property");
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPropertyThatDoesNotInfluenceHashCode.java // public class TestBeanWithPropertyThatDoesNotInfluenceHashCode { // // private Object property; // // public Object getProperty() { // return property; // } // // public void setProperty(Object property) { // this.property = property; // } // // @Override // public int hashCode() { // return 42; // } // } // Path: src/test/java/com/google/code/beanmatchers/HasValidBeanHashCodeForMatcherTest.java import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPropertyThatDoesNotInfluenceHashCode; import org.hamcrest.Description; import org.mockito.Mock; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class HasValidBeanHashCodeForMatcherTest { private HasValidBeanHashCodeForMatcher unitUnderTest; @Mock private TypeBasedValueGenerator valueGeneratorMock; @Mock private Object valueOne; @Mock private Object valueTwo; @Mock private Description descriptionMock; @BeforeMethod public void setUp() { initMocks(this); when(valueGeneratorMock.generate(Object.class)).thenReturn(valueOne, valueTwo, valueOne, valueTwo); when(descriptionMock.appendText(anyString())).thenReturn(descriptionMock); when(descriptionMock.appendValue(any())).thenReturn(descriptionMock); } @Test public void beanWithValidHashCodeShouldMatch() { // given Class beanType = TestBeanWithOneProperty.class; unitUnderTest = new HasValidBeanHashCodeForMatcher(valueGeneratorMock, "field1"); // when boolean match = unitUnderTest.matches(beanType); // then assertThat(match, is(true)); } @Test public void beanWithPropertyNotInfluencingHashCodeShouldNotMatch() { // given unitUnderTest = new HasValidBeanHashCodeForMatcher(valueGeneratorMock, "property");
Class beanType = TestBeanWithPropertyThatDoesNotInfluenceHashCode.class;
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/AbstractBeanEqualsMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // }
import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher;
.appendValue(property) .appendText(reason); } private Description describeBean(Class<T> beanType, Description description) { return description.appendText("bean of type ").appendValue(beanType.getName()); } private boolean equalsDoesNotHandleSameInstance(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); return !beanOne.equals(beanOne); } private boolean equalsDoesNotHandleNullValue(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); try { return beanOne.equals(null); } catch (Exception exception) { return true; } } private boolean equalsDoesNotHandleDifferingType(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); return beanOne.equals(new TestType()); } private boolean propertyNotComparedDuringEquals(Class<T> beanType, String property) { JavaBean beanOne = new JavaBean(beanType); Class<?> propertyType = beanOne.propertyType(property);
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // } // Path: src/main/java/com/google/code/beanmatchers/AbstractBeanEqualsMatcher.java import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; .appendValue(property) .appendText(reason); } private Description describeBean(Class<T> beanType, Description description) { return description.appendText("bean of type ").appendValue(beanType.getName()); } private boolean equalsDoesNotHandleSameInstance(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); return !beanOne.equals(beanOne); } private boolean equalsDoesNotHandleNullValue(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); try { return beanOne.equals(null); } catch (Exception exception) { return true; } } private boolean equalsDoesNotHandleDifferingType(Class<T> beanType) { JavaBean beanOne = new JavaBean(beanType); return beanOne.equals(new TestType()); } private boolean propertyNotComparedDuringEquals(Class<T> beanType, String property) { JavaBean beanOne = new JavaBean(beanType); Class<?> propertyType = beanOne.propertyType(property);
DistinctValues values = generateTwoDistinctValues(valueGenerator, propertyType);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/InstantiatingMatcherDecorator.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // }
import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher;
package com.google.code.beanmatchers; public class InstantiatingMatcherDecorator<T> extends TypeSafeMatcher<Class<T>> { private final Matcher<T> delegateMatcher; public InstantiatingMatcherDecorator(Matcher<T> matcher) { this.delegateMatcher = matcher; } @Override protected boolean matchesSafely(Class<T> beanType) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // Path: src/main/java/com/google/code/beanmatchers/InstantiatingMatcherDecorator.java import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; package com.google.code.beanmatchers; public class InstantiatingMatcherDecorator<T> extends TypeSafeMatcher<Class<T>> { private final Matcher<T> delegateMatcher; public InstantiatingMatcherDecorator(Matcher<T> matcher) { this.delegateMatcher = matcher; } @Override protected boolean matchesSafely(Class<T> beanType) {
T beanInstance = instantiateBean(beanType);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class BeanOperationsTest { @Test public void canInstantiateClassUsingNoArgsConstructor() { // when
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // } // Path: src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class BeanOperationsTest { @Test public void canInstantiateClassUsingNoArgsConstructor() { // when
TestBeanWithOneProperty bean = BeanOperations.instantiateBean(TestBeanWithOneProperty.class);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class BeanOperationsTest { @Test public void canInstantiateClassUsingNoArgsConstructor() { // when TestBeanWithOneProperty bean = BeanOperations.instantiateBean(TestBeanWithOneProperty.class); // then assertThat(bean, is(notNullValue())); } @Test public void canInstantiateClassUsingPrivateNoArgsConstructor() { // when
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // } // Path: src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class BeanOperationsTest { @Test public void canInstantiateClassUsingNoArgsConstructor() { // when TestBeanWithOneProperty bean = BeanOperations.instantiateBean(TestBeanWithOneProperty.class); // then assertThat(bean, is(notNullValue())); } @Test public void canInstantiateClassUsingPrivateNoArgsConstructor() { // when
TestBeanWithPrivateConstructor bean = BeanOperations.instantiateBean(TestBeanWithPrivateConstructor.class);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test;
public void canObtainPropertyDescriptorOfDefinedProperty() { // given TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); // when PropertyDescriptor[] properties = BeanOperations.propertyDescriptors(bean); // then assertThat(properties, hasItemInArray(hasProperty("name", equalTo("field1")))); } @Test public void canUseGetterToObtainPropertyValue() { // given Object expectedValue = "test value"; TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); bean.setField1(expectedValue); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "field1"); // when Object result = BeanOperations.invokeGetter(bean, propertyDescriptor); // then assertThat(result, is(expectedValue)); } @Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfGetterIsMissing() { // given Object value = "test value";
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // } // Path: src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test; public void canObtainPropertyDescriptorOfDefinedProperty() { // given TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); // when PropertyDescriptor[] properties = BeanOperations.propertyDescriptors(bean); // then assertThat(properties, hasItemInArray(hasProperty("name", equalTo("field1")))); } @Test public void canUseGetterToObtainPropertyValue() { // given Object expectedValue = "test value"; TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); bean.setField1(expectedValue); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "field1"); // when Object result = BeanOperations.invokeGetter(bean, propertyDescriptor); // then assertThat(result, is(expectedValue)); } @Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfGetterIsMissing() { // given Object value = "test value";
TestBeanWithMissingGetter bean = new TestBeanWithMissingGetter();
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test;
@Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfGetterIsMissing() { // given Object value = "test value"; TestBeanWithMissingGetter bean = new TestBeanWithMissingGetter(); bean.setBadField(value); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "badField"); // when BeanOperations.invokeGetter(bean, propertyDescriptor); } @Test public void canUseSetterToSetPropertyValue() { // given Object value = "test value"; TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "field1"); // when BeanOperations.invokeSetter(bean, propertyDescriptor, value); // then assertThat(bean.getField1(), is(value)); } @Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfSetterIsMissing() { // given Object value = "test value";
// Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingGetter.java // public class TestBeanWithMissingGetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public void setBadField(Object badField) { // this.badField = badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithMissingSetter.java // public class TestBeanWithMissingSetter { // // private Object goodField; // private Object badField; // // public Object getGoodField() { // return goodField; // } // // public void setGoodField(Object goodField) { // this.goodField = goodField; // } // // public Object getBadField() { // return badField; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithOneProperty.java // public class TestBeanWithOneProperty { // // private Object field1; // // public Object getField1() { // return field1; // } // // public void setField1(Object field1) { // this.field1 = field1; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestBeanWithOneProperty that = (TestBeanWithOneProperty) o; // // if (field1 != null ? !field1.equals(that.field1) : that.field1 != null) return false; // // return true; // } // // @Override // public int hashCode() { // return field1 != null ? field1.hashCode() : 0; // } // // @Override // public String toString() { // return getClass().getSimpleName() + "{field1=" + field1 + "}"; // } // } // // Path: src/test/java/com/google/code/beanmatchers/data/TestBeanWithPrivateConstructor.java // public class TestBeanWithPrivateConstructor { // private TestBeanWithPrivateConstructor() { // } // } // Path: src/test/java/com/google/code/beanmatchers/BeanOperationsTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import com.google.code.beanmatchers.data.TestBeanWithMissingGetter; import com.google.code.beanmatchers.data.TestBeanWithMissingSetter; import com.google.code.beanmatchers.data.TestBeanWithOneProperty; import com.google.code.beanmatchers.data.TestBeanWithPrivateConstructor; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.annotations.Test; @Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfGetterIsMissing() { // given Object value = "test value"; TestBeanWithMissingGetter bean = new TestBeanWithMissingGetter(); bean.setBadField(value); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "badField"); // when BeanOperations.invokeGetter(bean, propertyDescriptor); } @Test public void canUseSetterToSetPropertyValue() { // given Object value = "test value"; TestBeanWithOneProperty bean = new TestBeanWithOneProperty(); PropertyDescriptor propertyDescriptor = propertyDescriptor(bean, "field1"); // when BeanOperations.invokeSetter(bean, propertyDescriptor, value); // then assertThat(bean.getField1(), is(value)); } @Test(expectedExceptions = AccessorMissingException.class) public void shouldThrowExceptionIfSetterIsMissing() { // given Object value = "test value";
TestBeanWithMissingSetter bean = new TestBeanWithMissingSetter();
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/JavaBean.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // }
import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List;
package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean;
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // } // Path: src/main/java/com/google/code/beanmatchers/JavaBean.java import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List; package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean;
descriptors = propertyDescriptors(targetBean);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/JavaBean.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // }
import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List;
package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // } // Path: src/main/java/com/google/code/beanmatchers/JavaBean.java import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List; package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) {
this(instantiateBean(targetBeanType));
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/JavaBean.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // }
import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List;
package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) { this(instantiateBean(targetBeanType)); } public Class beanType() { return targetBean.getClass(); } public Class<?> propertyType(String propertyName) { return descriptorForName(propertyName).getPropertyType(); } public void setProperty(String propertyName, Object value) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // } // Path: src/main/java/com/google/code/beanmatchers/JavaBean.java import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List; package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) { this(instantiateBean(targetBeanType)); } public Class beanType() { return targetBean.getClass(); } public Class<?> propertyType(String propertyName) { return descriptorForName(propertyName).getPropertyType(); } public void setProperty(String propertyName, Object value) {
invokeSetter(targetBean, descriptorForName(propertyName), value);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/JavaBean.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // }
import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List;
package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) { this(instantiateBean(targetBeanType)); } public Class beanType() { return targetBean.getClass(); } public Class<?> propertyType(String propertyName) { return descriptorForName(propertyName).getPropertyType(); } public void setProperty(String propertyName, Object value) { invokeSetter(targetBean, descriptorForName(propertyName), value); } public Object getProperty(String propertyName) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> T instantiateBean(Class<T> beanClass) { // try { // Constructor<T> constructor = noArgsConstructor(beanClass); // constructor.setAccessible(true); // return constructor.newInstance(); // } catch (InstantiationException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (IllegalAccessException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } catch (InvocationTargetException exception) { // throw new BeanMatchersException( // "Could not instantiate bean with no-args constructor", exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeGetter(Object bean, PropertyDescriptor property) { // Method method = property.getReadMethod(); // if (method == null) { // throw new AccessorMissingException("missing getter for the property " + property.getName()); // } // return invokeMethod(bean, method); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static void invokeSetter(Object bean, PropertyDescriptor property, Object value) { // Method method = property.getWriteMethod(); // if (method == null) { // throw new AccessorMissingException("missing setter for the property " + property.getName()); // } // invokeMethod(bean, method, value); // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static <T> PropertyDescriptor[] propertyDescriptors(T bean) { // return propertyDescriptors(bean.getClass()); // } // Path: src/main/java/com/google/code/beanmatchers/JavaBean.java import static com.google.code.beanmatchers.BeanOperations.instantiateBean; import static com.google.code.beanmatchers.BeanOperations.invokeGetter; import static com.google.code.beanmatchers.BeanOperations.invokeSetter; import static com.google.code.beanmatchers.BeanOperations.propertyDescriptors; import java.beans.PropertyDescriptor; import java.util.List; package com.google.code.beanmatchers; class JavaBean { private final Object targetBean; private final PropertyDescriptor[] descriptors; public JavaBean(Object targetBean) { this.targetBean = targetBean; descriptors = propertyDescriptors(targetBean); } public JavaBean(Class targetBeanType) { this(instantiateBean(targetBeanType)); } public Class beanType() { return targetBean.getClass(); } public Class<?> propertyType(String propertyName) { return descriptorForName(propertyName).getPropertyType(); } public void setProperty(String propertyName, Object value) { invokeSetter(targetBean, descriptorForName(propertyName), value); } public Object getProperty(String propertyName) {
return invokeGetter(targetBean, descriptorForName(propertyName));
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/HasValidBeanEqualsExcludingMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static List<String> properties(Class<?> beanType) { // return properties(propertyDescriptors(beanType)); // }
import static com.google.code.beanmatchers.BeanOperations.properties; import static java.util.Arrays.asList; import java.util.List; import org.hamcrest.Description;
package com.google.code.beanmatchers; public class HasValidBeanEqualsExcludingMatcher<T> extends AbstractBeanEqualsMatcher<T> { private final List<String> excludedProperties; HasValidBeanEqualsExcludingMatcher( TypeBasedValueGenerator valueGenerator, String... excludedProperties) { super(valueGenerator); this.excludedProperties = asList(excludedProperties); } @Override protected boolean matchesSafely(Class<T> beanType, Description mismatchDescription) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static List<String> properties(Class<?> beanType) { // return properties(propertyDescriptors(beanType)); // } // Path: src/main/java/com/google/code/beanmatchers/HasValidBeanEqualsExcludingMatcher.java import static com.google.code.beanmatchers.BeanOperations.properties; import static java.util.Arrays.asList; import java.util.List; import org.hamcrest.Description; package com.google.code.beanmatchers; public class HasValidBeanEqualsExcludingMatcher<T> extends AbstractBeanEqualsMatcher<T> { private final List<String> excludedProperties; HasValidBeanEqualsExcludingMatcher( TypeBasedValueGenerator valueGenerator, String... excludedProperties) { super(valueGenerator); this.excludedProperties = asList(excludedProperties); } @Override protected boolean matchesSafely(Class<T> beanType, Description mismatchDescription) {
List<String> properties = properties(beanType);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/AbstractBeanAccessorMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Method getDeclaredMethod(Class type, String methodName, Class... argTypes) { // try { // return type.getDeclaredMethod(methodName, argTypes); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeMethod(Object bean, Method method, Object... args) { // try { // return method.invoke(bean, args); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // }
import static com.google.code.beanmatchers.BeanOperations.getDeclaredMethod; import static com.google.code.beanmatchers.BeanOperations.invokeMethod; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher;
.appendValue(bean.beanType().getName()) .appendText(" had an invalid getter/setter for the property ") .appendValue(property); return false; } } return true; } protected boolean beanDoesNotHaveValidGetterAndSetterForProperty(JavaBean bean, String property) { try { Class<?> propertyType = bean.propertyType(property); Object testValue = valueGenerator.generate(propertyType); bean.setProperty(property, testValue); Object result = bean.getProperty(property); boolean valid = Objects.equals(testValue, result); // for arrays fall back to compare element by element to allow for cloned arrays if (!valid && propertyType.isArray()) { valid = arraysEqual(propertyType, testValue, result); } return !valid; } catch (AccessorMissingException exception) { return true; } } private boolean arraysEqual(Class<?> arrayType, Object testValue, Object result) { Class<?> argumentType = arrayType.getComponentType().isPrimitive() ? arrayType : Object[].class;
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Method getDeclaredMethod(Class type, String methodName, Class... argTypes) { // try { // return type.getDeclaredMethod(methodName, argTypes); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeMethod(Object bean, Method method, Object... args) { // try { // return method.invoke(bean, args); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // Path: src/main/java/com/google/code/beanmatchers/AbstractBeanAccessorMatcher.java import static com.google.code.beanmatchers.BeanOperations.getDeclaredMethod; import static com.google.code.beanmatchers.BeanOperations.invokeMethod; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; .appendValue(bean.beanType().getName()) .appendText(" had an invalid getter/setter for the property ") .appendValue(property); return false; } } return true; } protected boolean beanDoesNotHaveValidGetterAndSetterForProperty(JavaBean bean, String property) { try { Class<?> propertyType = bean.propertyType(property); Object testValue = valueGenerator.generate(propertyType); bean.setProperty(property, testValue); Object result = bean.getProperty(property); boolean valid = Objects.equals(testValue, result); // for arrays fall back to compare element by element to allow for cloned arrays if (!valid && propertyType.isArray()) { valid = arraysEqual(propertyType, testValue, result); } return !valid; } catch (AccessorMissingException exception) { return true; } } private boolean arraysEqual(Class<?> arrayType, Object testValue, Object result) { Class<?> argumentType = arrayType.getComponentType().isPrimitive() ? arrayType : Object[].class;
Method method = getDeclaredMethod(Arrays.class, "equals", argumentType, argumentType);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/AbstractBeanAccessorMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Method getDeclaredMethod(Class type, String methodName, Class... argTypes) { // try { // return type.getDeclaredMethod(methodName, argTypes); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeMethod(Object bean, Method method, Object... args) { // try { // return method.invoke(bean, args); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // }
import static com.google.code.beanmatchers.BeanOperations.getDeclaredMethod; import static com.google.code.beanmatchers.BeanOperations.invokeMethod; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher;
.appendText(" had an invalid getter/setter for the property ") .appendValue(property); return false; } } return true; } protected boolean beanDoesNotHaveValidGetterAndSetterForProperty(JavaBean bean, String property) { try { Class<?> propertyType = bean.propertyType(property); Object testValue = valueGenerator.generate(propertyType); bean.setProperty(property, testValue); Object result = bean.getProperty(property); boolean valid = Objects.equals(testValue, result); // for arrays fall back to compare element by element to allow for cloned arrays if (!valid && propertyType.isArray()) { valid = arraysEqual(propertyType, testValue, result); } return !valid; } catch (AccessorMissingException exception) { return true; } } private boolean arraysEqual(Class<?> arrayType, Object testValue, Object result) { Class<?> argumentType = arrayType.getComponentType().isPrimitive() ? arrayType : Object[].class; Method method = getDeclaredMethod(Arrays.class, "equals", argumentType, argumentType);
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Method getDeclaredMethod(Class type, String methodName, Class... argTypes) { // try { // return type.getDeclaredMethod(methodName, argTypes); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // // Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static Object invokeMethod(Object bean, Method method, Object... args) { // try { // return method.invoke(bean, args); // } catch (Exception exception) { // throw new BeanMatchersException(exception); // } // } // Path: src/main/java/com/google/code/beanmatchers/AbstractBeanAccessorMatcher.java import static com.google.code.beanmatchers.BeanOperations.getDeclaredMethod; import static com.google.code.beanmatchers.BeanOperations.invokeMethod; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.hamcrest.Description; import org.hamcrest.DiagnosingMatcher; .appendText(" had an invalid getter/setter for the property ") .appendValue(property); return false; } } return true; } protected boolean beanDoesNotHaveValidGetterAndSetterForProperty(JavaBean bean, String property) { try { Class<?> propertyType = bean.propertyType(property); Object testValue = valueGenerator.generate(propertyType); bean.setProperty(property, testValue); Object result = bean.getProperty(property); boolean valid = Objects.equals(testValue, result); // for arrays fall back to compare element by element to allow for cloned arrays if (!valid && propertyType.isArray()) { valid = arraysEqual(propertyType, testValue, result); } return !valid; } catch (AccessorMissingException exception) { return true; } } private boolean arraysEqual(Class<?> arrayType, Object testValue, Object result) { Class<?> argumentType = arrayType.getComponentType().isPrimitive() ? arrayType : Object[].class; Method method = getDeclaredMethod(Arrays.class, "equals", argumentType, argumentType);
return (boolean) invokeMethod(null, method, testValue, result);
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/AbstractBeanHashCodeMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // }
import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher;
package com.google.code.beanmatchers; abstract class AbstractBeanHashCodeMatcher<T> extends TypeSafeDiagnosingMatcher<Class<T>> { final TypeBasedValueGenerator valueGenerator; AbstractBeanHashCodeMatcher(TypeBasedValueGenerator valueGenerator) { this.valueGenerator = valueGenerator; } protected boolean hashCodeIsInfluencedByProperties( JavaBean bean, List<String> properties, Description mismatchDescription) { for (String property : properties) { if (hashCodeNotInfluencedByProperty(bean, property)) { mismatchDescription .appendText("bean of type ") .appendValue(bean.beanType().getName()) .appendText(" had a hashCode not influenced by the property ") .appendValue(property); return false; } } return true; } private boolean hashCodeNotInfluencedByProperty(JavaBean bean, String property) { Class<?> propertyType = bean.propertyType(property);
// Path: src/main/java/com/google/code/beanmatchers/ValueGenerators.java // public static <T> DistinctValues<T> generateTwoDistinctValues( // TypeBasedValueGenerator valueGenerator, Class<T> valueType) { // int attempts = 0; // T valueOne = valueGenerator.generate(valueType); // T valueTwo; // do { // if (attempts == MAX_ATTEMPTS) { // throw new BeanMatchersException("Could not generate two distinct values after " // + MAX_ATTEMPTS + " attempts of type " + valueType.getName()); // } // valueTwo = valueGenerator.generate(valueType); // attempts++; // } while (valueOne.equals(valueTwo)); // return new DistinctValues<T>(valueOne, valueTwo); // } // Path: src/main/java/com/google/code/beanmatchers/AbstractBeanHashCodeMatcher.java import static com.google.code.beanmatchers.ValueGenerators.generateTwoDistinctValues; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; package com.google.code.beanmatchers; abstract class AbstractBeanHashCodeMatcher<T> extends TypeSafeDiagnosingMatcher<Class<T>> { final TypeBasedValueGenerator valueGenerator; AbstractBeanHashCodeMatcher(TypeBasedValueGenerator valueGenerator) { this.valueGenerator = valueGenerator; } protected boolean hashCodeIsInfluencedByProperties( JavaBean bean, List<String> properties, Description mismatchDescription) { for (String property : properties) { if (hashCodeNotInfluencedByProperty(bean, property)) { mismatchDescription .appendText("bean of type ") .appendValue(bean.beanType().getName()) .appendText(" had a hashCode not influenced by the property ") .appendValue(property); return false; } } return true; } private boolean hashCodeNotInfluencedByProperty(JavaBean bean, String property) { Class<?> propertyType = bean.propertyType(property);
DistinctValues values = generateTwoDistinctValues(valueGenerator, propertyType);
orien/bean-matchers
src/test/java/com/google/code/beanmatchers/MockingTypeBasedValueGeneratorTest.java
// Path: src/test/java/com/google/code/beanmatchers/ExtraMatchers.java // public static <T> Matcher<T> mock() { // return new BaseMatcher<T>() { // public boolean matches(Object o) { // return Mockito.mockingDetails(o).isMock(); // } // // public void describeTo(Description description) { // description.appendText("mock"); // } // }; // }
import static com.google.code.beanmatchers.ExtraMatchers.mock; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.testng.annotations.Test;
package com.google.code.beanmatchers; public class MockingTypeBasedValueGeneratorTest { @Test public void testGenerate() { // given TypeBasedValueGenerator unitUnderTest = new MockingTypeBasedValueGenerator(); // when Object value = unitUnderTest.generate(Object.class); // then
// Path: src/test/java/com/google/code/beanmatchers/ExtraMatchers.java // public static <T> Matcher<T> mock() { // return new BaseMatcher<T>() { // public boolean matches(Object o) { // return Mockito.mockingDetails(o).isMock(); // } // // public void describeTo(Description description) { // description.appendText("mock"); // } // }; // } // Path: src/test/java/com/google/code/beanmatchers/MockingTypeBasedValueGeneratorTest.java import static com.google.code.beanmatchers.ExtraMatchers.mock; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.testng.annotations.Test; package com.google.code.beanmatchers; public class MockingTypeBasedValueGeneratorTest { @Test public void testGenerate() { // given TypeBasedValueGenerator unitUnderTest = new MockingTypeBasedValueGenerator(); // when Object value = unitUnderTest.generate(Object.class); // then
assertThat(value, is(mock()));
orien/bean-matchers
src/main/java/com/google/code/beanmatchers/HasToStringDescribingPropertiesExcludingMatcher.java
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static List<String> properties(Class<?> beanType) { // return properties(propertyDescriptors(beanType)); // }
import static com.google.code.beanmatchers.BeanOperations.properties; import static java.util.Arrays.asList; import java.util.List; import org.hamcrest.Description;
package com.google.code.beanmatchers; public class HasToStringDescribingPropertiesExcludingMatcher<T> extends AbstractBeanToStringMatcher<T> { private final List<String> excludedProperties; public HasToStringDescribingPropertiesExcludingMatcher( TypeBasedValueGenerator valueGenerator, String... excludedProperties) { super(valueGenerator); this.excludedProperties = asList(excludedProperties); } @Override protected boolean matchesSafely(Class beanType, Description mismatchDescription) {
// Path: src/main/java/com/google/code/beanmatchers/BeanOperations.java // public static List<String> properties(Class<?> beanType) { // return properties(propertyDescriptors(beanType)); // } // Path: src/main/java/com/google/code/beanmatchers/HasToStringDescribingPropertiesExcludingMatcher.java import static com.google.code.beanmatchers.BeanOperations.properties; import static java.util.Arrays.asList; import java.util.List; import org.hamcrest.Description; package com.google.code.beanmatchers; public class HasToStringDescribingPropertiesExcludingMatcher<T> extends AbstractBeanToStringMatcher<T> { private final List<String> excludedProperties; public HasToStringDescribingPropertiesExcludingMatcher( TypeBasedValueGenerator valueGenerator, String... excludedProperties) { super(valueGenerator); this.excludedProperties = asList(excludedProperties); } @Override protected boolean matchesSafely(Class beanType, Description mismatchDescription) {
List<String> properties = properties(beanType);
sorinMD/MCTS
src/main/java/mcts/tree/node/TreeNode.java
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // }
import java.util.Arrays; import mcts.game.GameFactory;
package mcts.tree.node; /** * A tree node that only acts as a container for the statistics; i.e. the number * of wins/number of visits/prior value etc. * * @author sorinMD * */ public abstract class TreeNode { private final int[] state; private final int[] belief; int nVisits; double[] wins; int vLoss; private final int currentPlayer; private boolean leaf = true; private final boolean terminal; /** * Field required for ISMCTS way of computing parentVisits when this node was legal */ private int parentVisits; /** * Flag set when an external evaluation metric is used for seeding. */ private boolean evaluated = false; public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { this.state = state; this.belief = belief; this.terminal = terminal; currentPlayer = cpn; vLoss = 0; nVisits = 0; parentVisits = 0;
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // Path: src/main/java/mcts/tree/node/TreeNode.java import java.util.Arrays; import mcts.game.GameFactory; package mcts.tree.node; /** * A tree node that only acts as a container for the statistics; i.e. the number * of wins/number of visits/prior value etc. * * @author sorinMD * */ public abstract class TreeNode { private final int[] state; private final int[] belief; int nVisits; double[] wins; int vLoss; private final int currentPlayer; private boolean leaf = true; private final boolean terminal; /** * Field required for ISMCTS way of computing parentVisits when this node was legal */ private int parentVisits; /** * Flag set when an external evaluation metric is used for seeding. */ private boolean evaluated = false; public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { this.state = state; this.belief = belief; this.terminal = terminal; currentPlayer = cpn; vLoss = 0; nVisits = 0; parentVisits = 0;
wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game
sorinMD/MCTS
src/main/java/mcts/tree/update/UpdatePolicy.java
// Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // }
import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Selection;
package mcts.tree.update; /** * A utility for updating the tree nodes following a rollout result. * * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = StateUpdater.class), @Type(value = ActionUpdater.class), }) public abstract class UpdatePolicy { public boolean expectedReturn = false; public boolean everyVisit = false;
// Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // } // Path: src/main/java/mcts/tree/update/UpdatePolicy.java import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Selection; package mcts.tree.update; /** * A utility for updating the tree nodes following a rollout result. * * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = StateUpdater.class), @Type(value = ActionUpdater.class), }) public abstract class UpdatePolicy { public boolean expectedReturn = false; public boolean everyVisit = false;
public abstract void update(ArrayList<Selection> visited, double[] reward, int nRollouts);
sorinMD/MCTS
src/main/java/mcts/utils/Selection.java
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // }
import mcts.tree.node.TreeNode;
package mcts.utils; /** * Simple container needed for returning the result of the tree policy that * includes several pieces of information: the child node, a flag to indicate * whether all siblings have been explored and the action probability (given a belief). * * @author sorinMD * */ public class Selection { private boolean b = false;
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // Path: src/main/java/mcts/utils/Selection.java import mcts.tree.node.TreeNode; package mcts.utils; /** * Simple container needed for returning the result of the tree policy that * includes several pieces of information: the child node, a flag to indicate * whether all siblings have been explored and the action probability (given a belief). * * @author sorinMD * */ public class Selection { private boolean b = false;
private TreeNode node;
sorinMD/MCTS
src/main/java/mcts/tree/SimulationPolicy.java
// Path: src/main/java/mcts/game/Game.java // public interface Game { // // /** // * @return a clone of the game state // */ // public int[] getState(); // // public int getWinner(); // // public boolean isTerminal(); // // public int getCurrentPlayer(); // // /** // * Updates the state description based on the chosen action // * // * @param a // * the chosen action // * @param sample // * if this action was sampled according to an efficient game specific // * method or not. A simple rule of thumb is if the options were // * listed with sample true this should also be true and vice-versa. // */ // public void performAction(int[] a, boolean sample); // // /** // * @param sample // * flag for deciding if should include all actions or just sample // * from the legal ones. (e.g. usage: set to true if this is called // * while performing rollouts) // * @return a list of all the legal actions given the current state // */ // public Options listPossiblities(boolean sample); // // /** // * @return a clone of the game // */ // public Game copy(); // // /** // * Method for sampling the next action at random or based on the chances built // * into the game logic; // * // * @return the next action description // */ // public int[] sampleNextAction(); // // /** // * Method for sampling the next action at random or based on the chances built // * into the game logic; // * // * @return the index of the next legal action // */ // public int sampleNextActionIndex(); // // public TreeNode generateNode(); // // /** // * Executes one random action. // * // * @param belief // */ // public void gameTick(); // }
import mcts.game.Game;
package mcts.tree; /** * A utility for playing the game following a policy until max depth or a * terminal node is reached * TODO: set the maxDepth field via the configuration file * @author sorinMD * */ public class SimulationPolicy { private static int maxDepth = 100000; /** * Run the rollout policy to the end of the game * @param state * @return the game in the final state */
// Path: src/main/java/mcts/game/Game.java // public interface Game { // // /** // * @return a clone of the game state // */ // public int[] getState(); // // public int getWinner(); // // public boolean isTerminal(); // // public int getCurrentPlayer(); // // /** // * Updates the state description based on the chosen action // * // * @param a // * the chosen action // * @param sample // * if this action was sampled according to an efficient game specific // * method or not. A simple rule of thumb is if the options were // * listed with sample true this should also be true and vice-versa. // */ // public void performAction(int[] a, boolean sample); // // /** // * @param sample // * flag for deciding if should include all actions or just sample // * from the legal ones. (e.g. usage: set to true if this is called // * while performing rollouts) // * @return a list of all the legal actions given the current state // */ // public Options listPossiblities(boolean sample); // // /** // * @return a clone of the game // */ // public Game copy(); // // /** // * Method for sampling the next action at random or based on the chances built // * into the game logic; // * // * @return the next action description // */ // public int[] sampleNextAction(); // // /** // * Method for sampling the next action at random or based on the chances built // * into the game logic; // * // * @return the index of the next legal action // */ // public int sampleNextActionIndex(); // // public TreeNode generateNode(); // // /** // * Executes one random action. // * // * @param belief // */ // public void gameTick(); // } // Path: src/main/java/mcts/tree/SimulationPolicy.java import mcts.game.Game; package mcts.tree; /** * A utility for playing the game following a policy until max depth or a * terminal node is reached * TODO: set the maxDepth field via the configuration file * @author sorinMD * */ public class SimulationPolicy { private static int maxDepth = 100000; /** * Run the rollout policy to the end of the game * @param state * @return the game in the final state */
public static Game simulate(Game game){
sorinMD/MCTS
src/main/java/mcts/seeder/NullSeedTrigger.java
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // // Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // }
import mcts.game.GameFactory; import mcts.tree.node.TreeNode;
package mcts.seeder; /** * Null placeholder seeder when evaluation is not set. * * @author sorinMD * */ public class NullSeedTrigger extends SeedTrigger{ @Override
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // // Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // Path: src/main/java/mcts/seeder/NullSeedTrigger.java import mcts.game.GameFactory; import mcts.tree.node.TreeNode; package mcts.seeder; /** * Null placeholder seeder when evaluation is not set. * * @author sorinMD * */ public class NullSeedTrigger extends SeedTrigger{ @Override
public void addNode(TreeNode node, GameFactory gameFactory) {
sorinMD/MCTS
src/main/java/mcts/seeder/NullSeedTrigger.java
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // // Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // }
import mcts.game.GameFactory; import mcts.tree.node.TreeNode;
package mcts.seeder; /** * Null placeholder seeder when evaluation is not set. * * @author sorinMD * */ public class NullSeedTrigger extends SeedTrigger{ @Override
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // // Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // Path: src/main/java/mcts/seeder/NullSeedTrigger.java import mcts.game.GameFactory; import mcts.tree.node.TreeNode; package mcts.seeder; /** * Null placeholder seeder when evaluation is not set. * * @author sorinMD * */ public class NullSeedTrigger extends SeedTrigger{ @Override
public void addNode(TreeNode node, GameFactory gameFactory) {
sorinMD/MCTS
src/main/java/mcts/tree/update/StateUpdater.java
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // // Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import mcts.tree.node.TreeNode; import mcts.utils.Selection;
package mcts.tree.update; /** * Update rule with afterstates. * * @author sorinMD * */ public class StateUpdater extends UpdatePolicy{ public StateUpdater(boolean ex, boolean ev) { expectedReturn = ex; everyVisit = ev; } public StateUpdater() { // dummy constructor required for json.... } @Override
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // // Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // } // Path: src/main/java/mcts/tree/update/StateUpdater.java import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import mcts.tree.node.TreeNode; import mcts.utils.Selection; package mcts.tree.update; /** * Update rule with afterstates. * * @author sorinMD * */ public class StateUpdater extends UpdatePolicy{ public StateUpdater(boolean ex, boolean ev) { expectedReturn = ex; everyVisit = ev; } public StateUpdater() { // dummy constructor required for json.... } @Override
public void update(ArrayList<Selection> visited, double[] reward, int nRollouts) {
sorinMD/MCTS
src/main/java/mcts/tree/update/StateUpdater.java
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // // Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import mcts.tree.node.TreeNode; import mcts.utils.Selection;
package mcts.tree.update; /** * Update rule with afterstates. * * @author sorinMD * */ public class StateUpdater extends UpdatePolicy{ public StateUpdater(boolean ex, boolean ev) { expectedReturn = ex; everyVisit = ev; } public StateUpdater() { // dummy constructor required for json.... } @Override public void update(ArrayList<Selection> visited, double[] reward, int nRollouts) { if(expectedReturn) { //Use log probabilities for precision...this works for now as reward is between 0-1 TODO: separate probs and rewards for (int k =0; k < reward.length; k++) { reward[k] = Math.log(reward[k]); } if(everyVisit) { for(int i = visited.size()-1; i >= 0; i--) { double[] r = new double[reward.length]; for (int k =0; k < reward.length; k++) { r[k] = Math.exp(reward[k]); } visited.get(i).getNode().update(r, nRollouts); double logActProb = Math.log(visited.get(i).getActProb()); for (int k =0; k < reward.length; k++) { reward[k] += logActProb; } } }else {
// Path: src/main/java/mcts/tree/node/TreeNode.java // public abstract class TreeNode { // // private final int[] state; // private final int[] belief; // // int nVisits; // double[] wins; // int vLoss; // private final int currentPlayer; // private boolean leaf = true; // private final boolean terminal; // /** // * Field required for ISMCTS way of computing parentVisits when this node was legal // */ // private int parentVisits; // // /** // * Flag set when an external evaluation metric is used for seeding. // */ // private boolean evaluated = false; // // public TreeNode(int[] state, int[] belief, boolean terminal, int cpn) { // this.state = state; // this.belief = belief; // this.terminal = terminal; // currentPlayer = cpn; // vLoss = 0; // nVisits = 0; // parentVisits = 0; // wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game // } // // public int getCurrentPlayer(){ // return currentPlayer; // } // // /** // * @return a clone of the state // */ // public int[] getState(){ // return state.clone(); // } // // public boolean isLeaf(){ // return leaf; // } // // public void setLeaf(boolean leaf){ // this.leaf = leaf; // } // // public boolean isTerminal(){ // return terminal; // } // // public Key getKey(){ // return new Key(state, belief); // } // // /** // * Update this node and remove the virtual loss. // * // * TODO: it remains to be seen if synchronising makes this too slow... // * initial tests indicate this is a negligible increase, while it is // * beneficial to synchronise the updates so that no results are lost // */ // public synchronized void update(double[] reward, int nRollouts) { // for(int i = 0; i < wins.length; i++) // wins[i]+=reward[i]; // nVisits+=nRollouts; // vLoss = 0; // } // // public int getParentVisits() { // return parentVisits; // } // // public void incrementParentVisits() { // parentVisits++; // } // // public double getWins(int pn) { // return wins[pn]; // } // // public int getnVisits() { // return nVisits; // } // // public int getvLoss() { // return vLoss; // } // // public void setEvaluated(boolean evaluated){ // this.evaluated = evaluated; // } // // public boolean isEvaluated(){ // return evaluated; // } // // public void incrementVLoss(){ // this.vLoss++; // } // // /** // * Can this node be expanded? // * // * @return // */ // public abstract boolean canExpand(); // // @Override // public boolean equals(Object obj) { // if(obj instanceof TreeNode){ // return Arrays.equals(state, ((TreeNode) obj).state); // } // return false; // } // // @Override // public int hashCode() { // return Arrays.hashCode(state); // } // // } // // Path: src/main/java/mcts/utils/Selection.java // public class Selection { // // private boolean b = false; // private TreeNode node; // private double actProb; // // public Selection(boolean b, TreeNode node, double prob) { // this.b = b; // this.node = node; // this.actProb = prob; // } // // public boolean getBoolean() { // return b; // } // // public TreeNode getNode() { // return node; // } // // public double getActProb() { // return actProb; // } // } // Path: src/main/java/mcts/tree/update/StateUpdater.java import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import mcts.tree.node.TreeNode; import mcts.utils.Selection; package mcts.tree.update; /** * Update rule with afterstates. * * @author sorinMD * */ public class StateUpdater extends UpdatePolicy{ public StateUpdater(boolean ex, boolean ev) { expectedReturn = ex; everyVisit = ev; } public StateUpdater() { // dummy constructor required for json.... } @Override public void update(ArrayList<Selection> visited, double[] reward, int nRollouts) { if(expectedReturn) { //Use log probabilities for precision...this works for now as reward is between 0-1 TODO: separate probs and rewards for (int k =0; k < reward.length; k++) { reward[k] = Math.log(reward[k]); } if(everyVisit) { for(int i = visited.size()-1; i >= 0; i--) { double[] r = new double[reward.length]; for (int k =0; k < reward.length; k++) { r[k] = Math.exp(reward[k]); } visited.get(i).getNode().update(r, nRollouts); double logActProb = Math.log(visited.get(i).getActProb()); for (int k =0; k < reward.length; k++) { reward[k] += logActProb; } } }else {
HashMap<TreeNode, double[]> updateValues = new HashMap<>();
sorinMD/MCTS
src/main/java/mcts/game/NullDeterminizationSampler.java
// Path: src/main/java/mcts/utils/GameSample.java // public class GameSample { // private Game game; // private double prob; // // public GameSample(Game g, double p) { // game = g; // prob = p; // } // // public Game getGame() { // return game; // } // // public double getProb() { // return prob; // } // }
import mcts.utils.GameSample;
package mcts.game; public class NullDeterminizationSampler implements DeterminizationSampler{ @Override
// Path: src/main/java/mcts/utils/GameSample.java // public class GameSample { // private Game game; // private double prob; // // public GameSample(Game g, double p) { // game = g; // prob = p; // } // // public Game getGame() { // return game; // } // // public double getProb() { // return prob; // } // } // Path: src/main/java/mcts/game/NullDeterminizationSampler.java import mcts.utils.GameSample; package mcts.game; public class NullDeterminizationSampler implements DeterminizationSampler{ @Override
public GameSample sampleObservableState(Game currentGame, GameFactory factory) {
sorinMD/MCTS
src/main/java/mcts/seeder/Seeder.java
// Path: src/main/java/mcts/utils/Priority.java // public enum Priority { // HIGHEST(0), // HIGH(1), // MEDIUM(2), // LOW(3), // LOWEST(4); // // int value; // // Priority(int val) { // this.value = val; // } // // public int getValue(){ // return value; // } // } // // Path: src/main/java/mcts/utils/PriorityRunnable.java // public interface PriorityRunnable { // // int getPriority(); // // }
import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Priority; import mcts.utils.PriorityRunnable;
package mcts.seeder; /** * Abstract class for the runnable that executes the seeding code. * By default the seeding cods has a higher priority over the search * or it would never be executed. * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ })
// Path: src/main/java/mcts/utils/Priority.java // public enum Priority { // HIGHEST(0), // HIGH(1), // MEDIUM(2), // LOW(3), // LOWEST(4); // // int value; // // Priority(int val) { // this.value = val; // } // // public int getValue(){ // return value; // } // } // // Path: src/main/java/mcts/utils/PriorityRunnable.java // public interface PriorityRunnable { // // int getPriority(); // // } // Path: src/main/java/mcts/seeder/Seeder.java import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Priority; import mcts.utils.PriorityRunnable; package mcts.seeder; /** * Abstract class for the runnable that executes the seeding code. * By default the seeding cods has a higher priority over the search * or it would never be executed. * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ })
public abstract class Seeder implements Runnable, PriorityRunnable{
sorinMD/MCTS
src/main/java/mcts/seeder/Seeder.java
// Path: src/main/java/mcts/utils/Priority.java // public enum Priority { // HIGHEST(0), // HIGH(1), // MEDIUM(2), // LOW(3), // LOWEST(4); // // int value; // // Priority(int val) { // this.value = val; // } // // public int getValue(){ // return value; // } // } // // Path: src/main/java/mcts/utils/PriorityRunnable.java // public interface PriorityRunnable { // // int getPriority(); // // }
import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Priority; import mcts.utils.PriorityRunnable;
package mcts.seeder; /** * Abstract class for the runnable that executes the seeding code. * By default the seeding cods has a higher priority over the search * or it would never be executed. * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ }) public abstract class Seeder implements Runnable, PriorityRunnable{
// Path: src/main/java/mcts/utils/Priority.java // public enum Priority { // HIGHEST(0), // HIGH(1), // MEDIUM(2), // LOW(3), // LOWEST(4); // // int value; // // Priority(int val) { // this.value = val; // } // // public int getValue(){ // return value; // } // } // // Path: src/main/java/mcts/utils/PriorityRunnable.java // public interface PriorityRunnable { // // int getPriority(); // // } // Path: src/main/java/mcts/seeder/Seeder.java import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.utils.Priority; import mcts.utils.PriorityRunnable; package mcts.seeder; /** * Abstract class for the runnable that executes the seeding code. * By default the seeding cods has a higher priority over the search * or it would never be executed. * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ }) public abstract class Seeder implements Runnable, PriorityRunnable{
private static Priority priority = Priority.HIGH;
sorinMD/MCTS
src/main/java/mcts/tree/node/StandardNode.java
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // }
import java.util.ArrayList; import java.util.Arrays; import com.google.common.util.concurrent.AtomicDoubleArray; import mcts.game.GameFactory;
package mcts.tree.node; /** * Standard non-chance node that can be expanded normally and the tree policy can be deterministic. * TODO: separate the P (exploration) and the Q (value for exploitation) * @author sorinMD * */ public class StandardNode extends TreeNode{ private ArrayList<Key> children; /** * The possible actions. */ private ArrayList<int[]> actions; /** * The probabilities of actions to be legal. */ private ArrayList<Double> actionProbs; //stats on actions required if afterstates are not used public int[] childVisits; public double[][] wins; public int[] vloss; /** * The P value (probability of selecting each action given a policy) of each * action in the same order as the children are set. At the moment this is * also used as value initialisation */ public AtomicDoubleArray pValue; public StandardNode(int[] state, int[] belief, boolean terminal, int cpn) { super(state, belief, terminal, cpn); } /** * Adds the edges to the node. * @param children */ public synchronized void addChildren(ArrayList<Key> children, ArrayList<int[]> acts, ArrayList<Double> actionProbs){ if(!isLeaf()) return; this.actions = acts; this.children = children; this.actionProbs = actionProbs; //initialise the pValue with a uniform distribution double[] dist = new double[children.size()]; Arrays.fill(dist, 1.0/children.size()); pValue = new AtomicDoubleArray(dist); //stats on actions required only if afterstates are not used childVisits = new int[children.size()];
// Path: src/main/java/mcts/game/GameFactory.java // public class GameFactory { // public static final int TICTACTOE = 0; // public static final int CATAN = 1; // // private GameConfig gameConfig; // private Belief belief; // // public GameFactory(GameConfig gameConfig, Belief belief) { // this.gameConfig = gameConfig; // this.belief = belief; // } // // public Game getNewGame(){ // if(gameConfig.id == CATAN){ // if(belief != null) { // if(!CatanWithBelief.board.init) // CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board. // return new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // }else { // if(!Catan.board.init) // Catan.initBoard(); // return new Catan(((CatanConfig) gameConfig)); // } // }else // return new TicTacToe(); // } // // public Game getGame(int[] state){ // if(gameConfig.id == CATAN){ // if(belief != null) // return new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief); // else // return new Catan(state, ((CatanConfig) gameConfig)); // }else // return new TicTacToe(state); // } // // public GameConfig getConfig(){ // return gameConfig; // } // // public Belief getBelief() { // return belief; // } // // public DeterminizationSampler getDeterminizationSampler() { // if(gameConfig.id == CATAN && belief != null) // return new CatanDeterminizationSampler(); // return new NullDeterminizationSampler(); // } // // /** // * @return // */ // public static int nMaxPlayers(){ // return 4; // } // // public GameFactory copy() { // Belief clone = null; // if(belief != null) // clone = belief.copy(); // GameFactory factory = new GameFactory(gameConfig.copy(), clone); // return factory; // } // // } // Path: src/main/java/mcts/tree/node/StandardNode.java import java.util.ArrayList; import java.util.Arrays; import com.google.common.util.concurrent.AtomicDoubleArray; import mcts.game.GameFactory; package mcts.tree.node; /** * Standard non-chance node that can be expanded normally and the tree policy can be deterministic. * TODO: separate the P (exploration) and the Q (value for exploitation) * @author sorinMD * */ public class StandardNode extends TreeNode{ private ArrayList<Key> children; /** * The possible actions. */ private ArrayList<int[]> actions; /** * The probabilities of actions to be legal. */ private ArrayList<Double> actionProbs; //stats on actions required if afterstates are not used public int[] childVisits; public double[][] wins; public int[] vloss; /** * The P value (probability of selecting each action given a policy) of each * action in the same order as the children are set. At the moment this is * also used as value initialisation */ public AtomicDoubleArray pValue; public StandardNode(int[] state, int[] belief, boolean terminal, int cpn) { super(state, belief, terminal, cpn); } /** * Adds the edges to the node. * @param children */ public synchronized void addChildren(ArrayList<Key> children, ArrayList<int[]> acts, ArrayList<Double> actionProbs){ if(!isLeaf()) return; this.actions = acts; this.children = children; this.actionProbs = actionProbs; //initialise the pValue with a uniform distribution double[] dist = new double[children.size()]; Arrays.fill(dist, 1.0/children.size()); pValue = new AtomicDoubleArray(dist); //stats on actions required only if afterstates are not used childVisits = new int[children.size()];
wins = new double[GameFactory.nMaxPlayers()][];
Neticoa/cxx-maven-plugin
src/main/java/org/apache/maven/plugin/cxx/PerformBranchMojo.java
// Path: src/main/java/org/apache/maven/plugin/cxx/utils/release/CxxReleaseDescriptor.java // public class CxxReleaseDescriptor extends ReleaseDescriptor // { // /** // * run cycle in simulation mode // */ // private boolean dryRun = true; // // public void setDryRun( boolean dryRun ) // { // this.dryRun = dryRun; // } // // public boolean getDryRun( ) // { // return dryRun; // } // // /** // * new main artifactId if any // */ // private String artifactId = null; // // public void setArtifactId( String artifactId ) // { // this.artifactId = artifactId; // } // // public String getArtifactId( ) // { // return artifactId; // } // // /** // * // */ // private boolean snapshotDevelopmentVersion = false; // // public void setSnapshotDevelopmentVersion( boolean snapshotDevelopmentVersion ) // { // this.snapshotDevelopmentVersion = snapshotDevelopmentVersion; // } // // public boolean isSnapshotDevelopmentVersion( ) // { // return snapshotDevelopmentVersion; // } // // }
import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.cxx.utils.release.CxxReleaseDescriptor;
package org.apache.maven.plugin.cxx; /* * Copyright (C) 2011-2016, Neticoa SAS France - Tous droits réservés. * Author(s) : Franck Bonin, Neticoa SAS France * * 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. * */ /** * Branch a project in SCM * * @author * @version * @since 0.0.6 */ @Mojo( name = "branch", aggregator = true ) public class PerformBranchMojo extends AbstractPerformBranchReleaseMojo { /** * Whether to update versions in the working copy. * * @since 0.0.6 */ @Parameter( defaultValue = "false", property = "updateWorkingCopyVersions" ) private boolean updateWorkingCopyVersions; /** * Whether to update versions in the branch. * * @since 0.0.6 */ @Parameter( defaultValue = "true", property = "updateBranchVersions" ) private boolean updateBranchVersions; /** * Specify the new version for the branch. * This parameter is only meaningful if {@link #updateBranchVersions} = {@code true}. * * @since 0.0.6 */ @Parameter( property = "branchVersion" ) private String branchVersion; /** * The branch name to use. * * @required * @since 0.0.6 */ @Parameter( property = "branchLabel", alias = "branchName", required = true ) private String branchLabel; /** * The branch base directory in SVN, you must define it if you don't use the standard svn layout * (trunk/tags/branches). For example, <code>http://svn.apache.org/repos/asf/maven/plugins/branches</code>. The URL * is an SVN URL and does not include the SCM provider and protocol. * * @since 0.0.6 */ @Parameter( property = "branchBase" ) protected String branchBase; /** * Whether to update to SNAPSHOT versions in the branch. * * @since 0.0.6 */ @Parameter( defaultValue = "false", property = "updateVersionsToSnapshot" ) protected boolean updateVersionsToSnapshot; @Override
// Path: src/main/java/org/apache/maven/plugin/cxx/utils/release/CxxReleaseDescriptor.java // public class CxxReleaseDescriptor extends ReleaseDescriptor // { // /** // * run cycle in simulation mode // */ // private boolean dryRun = true; // // public void setDryRun( boolean dryRun ) // { // this.dryRun = dryRun; // } // // public boolean getDryRun( ) // { // return dryRun; // } // // /** // * new main artifactId if any // */ // private String artifactId = null; // // public void setArtifactId( String artifactId ) // { // this.artifactId = artifactId; // } // // public String getArtifactId( ) // { // return artifactId; // } // // /** // * // */ // private boolean snapshotDevelopmentVersion = false; // // public void setSnapshotDevelopmentVersion( boolean snapshotDevelopmentVersion ) // { // this.snapshotDevelopmentVersion = snapshotDevelopmentVersion; // } // // public boolean isSnapshotDevelopmentVersion( ) // { // return snapshotDevelopmentVersion; // } // // } // Path: src/main/java/org/apache/maven/plugin/cxx/PerformBranchMojo.java import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.cxx.utils.release.CxxReleaseDescriptor; package org.apache.maven.plugin.cxx; /* * Copyright (C) 2011-2016, Neticoa SAS France - Tous droits réservés. * Author(s) : Franck Bonin, Neticoa SAS France * * 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. * */ /** * Branch a project in SCM * * @author * @version * @since 0.0.6 */ @Mojo( name = "branch", aggregator = true ) public class PerformBranchMojo extends AbstractPerformBranchReleaseMojo { /** * Whether to update versions in the working copy. * * @since 0.0.6 */ @Parameter( defaultValue = "false", property = "updateWorkingCopyVersions" ) private boolean updateWorkingCopyVersions; /** * Whether to update versions in the branch. * * @since 0.0.6 */ @Parameter( defaultValue = "true", property = "updateBranchVersions" ) private boolean updateBranchVersions; /** * Specify the new version for the branch. * This parameter is only meaningful if {@link #updateBranchVersions} = {@code true}. * * @since 0.0.6 */ @Parameter( property = "branchVersion" ) private String branchVersion; /** * The branch name to use. * * @required * @since 0.0.6 */ @Parameter( property = "branchLabel", alias = "branchName", required = true ) private String branchLabel; /** * The branch base directory in SVN, you must define it if you don't use the standard svn layout * (trunk/tags/branches). For example, <code>http://svn.apache.org/repos/asf/maven/plugins/branches</code>. The URL * is an SVN URL and does not include the SCM provider and protocol. * * @since 0.0.6 */ @Parameter( property = "branchBase" ) protected String branchBase; /** * Whether to update to SNAPSHOT versions in the branch. * * @since 0.0.6 */ @Parameter( defaultValue = "false", property = "updateVersionsToSnapshot" ) protected boolean updateVersionsToSnapshot; @Override
protected CxxReleaseDescriptor createReleaseDescriptor()
Neticoa/cxx-maven-plugin
src/main/java/org/codehaus/plexus/archiver/manager/ArchiveContentListerManager.java
// Path: src/main/java/org/codehaus/plexus/archiver/ArchiveContentLister.java // public interface ArchiveContentLister // { // String ROLE = ArchiveContentLister.class.getName(); // // /** // * list the archive content. // * // * @throws ArchiverException // */ // List<ArchiveContentEntry> list() // throws ArchiverException; // // /* // * Take a path into the archive and list it (futur). // * // * @param path // * Path inside the archive to be listed. // * @throws ArchiverException // */ // /*void extract( String path ) // throws ArchiverException;*/ // // File getSourceFile(); // // void setSourceFile( File sourceFile ); // // /** // * Sets a set of {@link FileSelector} instances, which may be used to select the files to extract from the archive. // * If file selectors are present, then a file is only extracted, if it is confirmed by all file selectors. // */ // void setFileSelectors( FileSelector[] selectors ); // // /** // * Returns a set of {@link FileSelector} instances, which may be used to select the files to extract from the // * archive. If file selectors are present, then a file is only extracted, if it is confirmed by all file selectors. // */ // FileSelector[] getFileSelectors(); // }
import org.codehaus.plexus.archiver.ArchiveContentLister; import java.io.File;
package org.codehaus.plexus.archiver.manager; /* * Copyright (C) 2011-2016, Neticoa SAS France - Tous droits réservés. * Author(s) : Franck Bonin, Neticoa SAS France * * 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. * */ //import javax.annotation.Nonnull; /** * @author Franck Bonin * @version $Revision$ $Date$ */ public interface ArchiveContentListerManager { String ROLE = ArchiveContentListerManager.class.getName();
// Path: src/main/java/org/codehaus/plexus/archiver/ArchiveContentLister.java // public interface ArchiveContentLister // { // String ROLE = ArchiveContentLister.class.getName(); // // /** // * list the archive content. // * // * @throws ArchiverException // */ // List<ArchiveContentEntry> list() // throws ArchiverException; // // /* // * Take a path into the archive and list it (futur). // * // * @param path // * Path inside the archive to be listed. // * @throws ArchiverException // */ // /*void extract( String path ) // throws ArchiverException;*/ // // File getSourceFile(); // // void setSourceFile( File sourceFile ); // // /** // * Sets a set of {@link FileSelector} instances, which may be used to select the files to extract from the archive. // * If file selectors are present, then a file is only extracted, if it is confirmed by all file selectors. // */ // void setFileSelectors( FileSelector[] selectors ); // // /** // * Returns a set of {@link FileSelector} instances, which may be used to select the files to extract from the // * archive. If file selectors are present, then a file is only extracted, if it is confirmed by all file selectors. // */ // FileSelector[] getFileSelectors(); // } // Path: src/main/java/org/codehaus/plexus/archiver/manager/ArchiveContentListerManager.java import org.codehaus.plexus.archiver.ArchiveContentLister; import java.io.File; package org.codehaus.plexus.archiver.manager; /* * Copyright (C) 2011-2016, Neticoa SAS France - Tous droits réservés. * Author(s) : Franck Bonin, Neticoa SAS France * * 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. * */ //import javax.annotation.Nonnull; /** * @author Franck Bonin * @version $Revision$ $Date$ */ public interface ArchiveContentListerManager { String ROLE = ArchiveContentListerManager.class.getName();
ArchiveContentLister getArchiveContentLister( String archiveContentListerName )
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/SolidityUtils.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/sha3/Sha3.java // public abstract class Sha3 { // // public static String hash(String value) { // byte[] b = value.getBytes(); // String s = getHexStringByByteArray(b); // // Keccak keccak = new Keccak(1600); // return keccak.getHash(s, 1088, 32); // // } // // private static String getHexStringByByteArray(byte[] array) { // if (array == null) { // return null; // } // StringBuilder stringBuilder = new StringBuilder(array.length * 2); // @SuppressWarnings("resource") // Formatter formatter = new Formatter(stringBuilder); // for (byte tempByte : array) { // formatter.format("%02x", tempByte); // } // // return stringBuilder.toString(); // } // // }
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.HashMap; import java.util.regex.Pattern; import io.ethmobile.ethdroid.sha3.Sha3;
return valueBD.add(new BigDecimal(complement)).add(new BigDecimal(1)); } return valueBD; } public static boolean isStrictAddress(String value) { Pattern p = Pattern.compile("^0x[0-9a-f]{40}$", Pattern.CASE_INSENSITIVE); return p.matcher(value).matches(); } public static boolean isAddress(String value) { Pattern requirementsPattern = Pattern.compile("^(0x)?[0-9a-f]{40}$", Pattern.CASE_INSENSITIVE); boolean requirements = requirementsPattern.matcher(value).matches(); if (!requirements) { return false; // } Pattern allCaps = Pattern.compile("^(0x)?[0-9A-F]{40}$"); boolean isallCaps = allCaps.matcher(value).matches(); Pattern allLowers = Pattern.compile("^(0x)?[0-9a-f]{40}$"); boolean isallLowers = allLowers.matcher(value).matches(); if (isallCaps || isallLowers) { return true; } return isChecksumAddress(value); } public static boolean isChecksumAddress(String value) { if (value == null) return false; value = value.replace("0x", "");
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/sha3/Sha3.java // public abstract class Sha3 { // // public static String hash(String value) { // byte[] b = value.getBytes(); // String s = getHexStringByByteArray(b); // // Keccak keccak = new Keccak(1600); // return keccak.getHash(s, 1088, 32); // // } // // private static String getHexStringByByteArray(byte[] array) { // if (array == null) { // return null; // } // StringBuilder stringBuilder = new StringBuilder(array.length * 2); // @SuppressWarnings("resource") // Formatter formatter = new Formatter(stringBuilder); // for (byte tempByte : array) { // formatter.format("%02x", tempByte); // } // // return stringBuilder.toString(); // } // // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/SolidityUtils.java import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.HashMap; import java.util.regex.Pattern; import io.ethmobile.ethdroid.sha3.Sha3; return valueBD.add(new BigDecimal(complement)).add(new BigDecimal(1)); } return valueBD; } public static boolean isStrictAddress(String value) { Pattern p = Pattern.compile("^0x[0-9a-f]{40}$", Pattern.CASE_INSENSITIVE); return p.matcher(value).matches(); } public static boolean isAddress(String value) { Pattern requirementsPattern = Pattern.compile("^(0x)?[0-9a-f]{40}$", Pattern.CASE_INSENSITIVE); boolean requirements = requirementsPattern.matcher(value).matches(); if (!requirements) { return false; // } Pattern allCaps = Pattern.compile("^(0x)?[0-9A-F]{40}$"); boolean isallCaps = allCaps.matcher(value).matches(); Pattern allLowers = Pattern.compile("^(0x)?[0-9a-f]{40}$"); boolean isallLowers = allLowers.matcher(value).matches(); if (isallCaps || isallLowers) { return true; } return isChecksumAddress(value); } public static boolean isChecksumAddress(String value) { if (value == null) return false; value = value.replace("0x", "");
String hash = Sha3.hash(value.toLowerCase());
ethmobile/ethdroid
ethdroid/src/androidTest/java/io/ethmobile/ethdroid/EthDroidTest.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.util.concurrent.TimeUnit;
package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ @RunWith(AndroidJUnit4.class) public class EthDroidTest { private Context appContext; private EthDroid ethdroid; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); String datadir = appContext.getFilesDir().getAbsolutePath();
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // } // Path: ethdroid/src/androidTest/java/io/ethmobile/ethdroid/EthDroidTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.util.concurrent.TimeUnit; package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ @RunWith(AndroidJUnit4.class) public class EthDroidTest { private Context appContext; private EthDroid ethdroid; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); String datadir = appContext.getFilesDir().getAbsolutePath();
deleteDirIfExists(new File(datadir + "/GethDroid"));
ethmobile/ethdroid
ethdroid/src/androidTest/java/io/ethmobile/ethdroid/KeyManagerTest.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import org.ethereum.geth.Account; import org.ethereum.geth.Address; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit;
package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ public class KeyManagerTest { private static final String PASSWORD = "password"; private Context appContext; private String datadir; private KeyManager keyManager; private Account account; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); datadir = appContext.getFilesDir().getAbsolutePath();
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // } // Path: ethdroid/src/androidTest/java/io/ethmobile/ethdroid/KeyManagerTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import org.ethereum.geth.Account; import org.ethereum.geth.Address; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ public class KeyManagerTest { private static final String PASSWORD = "password"; private Context appContext; private String datadir; private KeyManager keyManager; private Account account; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); datadir = appContext.getFilesDir().getAbsolutePath();
deleteDirIfExists(new File(datadir + "/keystore"));
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SUInt.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // }
import java.math.BigInteger; import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException;
package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 16/08/16. */ public abstract class SUInt<T> extends SType<T> { private SUInt(T value) { super(value); } public static SUInt8 fromShort(short from) { if (from < 0) {
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SUInt.java import java.math.BigInteger; import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException; package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 16/08/16. */ public abstract class SUInt<T> extends SType<T> { private SUInt(T value) { super(value); } public static SUInt8 fromShort(short from) { if (from < 0) {
throw new EthDroidException("illegal argument. " + from + " is negative");
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/KeyManager.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/sha3/Sha3.java // public abstract class Sha3 { // // public static String hash(String value) { // byte[] b = value.getBytes(); // String s = getHexStringByByteArray(b); // // Keccak keccak = new Keccak(1600); // return keccak.getHash(s, 1088, 32); // // } // // private static String getHexStringByByteArray(byte[] array) { // if (array == null) { // return null; // } // StringBuilder stringBuilder = new StringBuilder(array.length * 2); // @SuppressWarnings("resource") // Formatter formatter = new Formatter(stringBuilder); // for (byte tempByte : array) { // formatter.format("%02x", tempByte); // } // // return stringBuilder.toString(); // } // // }
import org.ethereum.geth.Account; import org.ethereum.geth.Accounts; import org.ethereum.geth.Geth; import org.ethereum.geth.KeyStore; import java.io.File; import java.util.ArrayList; import java.util.List; import io.ethmobile.ethdroid.sha3.Sha3;
return true; } } // removes the private key with the given address from memory. public void lockAccount(Account account) throws Exception { keystore.lock(account.getAddress()); } // unlockAccountDuring with 0 as duration public void unlockAccount(Account account, String passphrase) throws Exception { keystore.unlock(account, passphrase); } // seconds == 0 : until program exits public void unlockAccountDuring(Account account, String passphrase, long seconds) throws Exception { keystore.timedUnlock(account, passphrase, (long) (seconds * Math.pow(10, 9))); } public void deleteAccount(Account account, String passphrase) throws Exception { keystore.deleteAccount(account, passphrase); } public void updateAccountPassphrase(Account account, String passphrase, String newPassphrase) throws Exception { keystore.updateAccount(account, passphrase, newPassphrase); } public byte[] signString(Account account, String toSign) throws Exception {
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/sha3/Sha3.java // public abstract class Sha3 { // // public static String hash(String value) { // byte[] b = value.getBytes(); // String s = getHexStringByByteArray(b); // // Keccak keccak = new Keccak(1600); // return keccak.getHash(s, 1088, 32); // // } // // private static String getHexStringByByteArray(byte[] array) { // if (array == null) { // return null; // } // StringBuilder stringBuilder = new StringBuilder(array.length * 2); // @SuppressWarnings("resource") // Formatter formatter = new Formatter(stringBuilder); // for (byte tempByte : array) { // formatter.format("%02x", tempByte); // } // // return stringBuilder.toString(); // } // // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/KeyManager.java import org.ethereum.geth.Account; import org.ethereum.geth.Accounts; import org.ethereum.geth.Geth; import org.ethereum.geth.KeyStore; import java.io.File; import java.util.ArrayList; import java.util.List; import io.ethmobile.ethdroid.sha3.Sha3; return true; } } // removes the private key with the given address from memory. public void lockAccount(Account account) throws Exception { keystore.lock(account.getAddress()); } // unlockAccountDuring with 0 as duration public void unlockAccount(Account account, String passphrase) throws Exception { keystore.unlock(account, passphrase); } // seconds == 0 : until program exits public void unlockAccountDuring(Account account, String passphrase, long seconds) throws Exception { keystore.timedUnlock(account, passphrase, (long) (seconds * Math.pow(10, 9))); } public void deleteAccount(Account account, String passphrase) throws Exception { keystore.deleteAccount(account, passphrase); } public void updateAccountPassphrase(Account account, String passphrase, String newPassphrase) throws Exception { keystore.updateAccount(account, passphrase, newPassphrase); } public byte[] signString(Account account, String toSign) throws Exception {
String hash = Sha3.hash(toSign);
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SAddress.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // }
import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException;
package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 5/08/16. */ public class SAddress extends SType<String> { private SAddress(String address) { super(address); }
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SAddress.java import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException; package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 5/08/16. */ public class SAddress extends SType<String> { private SAddress(String address) { super(address); }
public static SAddress fromString(String from) throws EthDroidException {
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SArray.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import io.ethmobile.ethdroid.exception.EthDroidException;
package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 07/02/17. */ public class SArray<T extends SType> extends SType<T[]> { private int fixedSize; private SArray(T[] value, int _fixedSize) { super(value); fixedSize = _fixedSize; } public static <T extends SType> SArray<T> fromArray(T[] array) { return new SArray<>(array, array.length); } public static <T extends SType> SArray<T> fromList(List<T> list) { T[] ret = (T[]) Array.newInstance(T.getClazz(), list.size()); for (int i = 0; i < list.size(); i++) { ret[i] = list.get(i); } return new SArray<>(ret, -1); } public static Class<? extends SType> getNestedType(Type type) { if (type instanceof ParameterizedType) { return SArray.getNestedType(((ParameterizedType) type).getActualTypeArguments()[0]); } else if (type instanceof Class) { return (Class<? extends SType>) type; } else {
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SArray.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import io.ethmobile.ethdroid.exception.EthDroidException; package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 07/02/17. */ public class SArray<T extends SType> extends SType<T[]> { private int fixedSize; private SArray(T[] value, int _fixedSize) { super(value); fixedSize = _fixedSize; } public static <T extends SType> SArray<T> fromArray(T[] array) { return new SArray<>(array, array.length); } public static <T extends SType> SArray<T> fromList(List<T> list) { T[] ret = (T[]) Array.newInstance(T.getClazz(), list.size()); for (int i = 0; i < list.size(); i++) { ret[i] = list.get(i); } return new SArray<>(ret, -1); } public static Class<? extends SType> getNestedType(Type type) { if (type instanceof ParameterizedType) { return SArray.getNestedType(((ParameterizedType) type).getActualTypeArguments()[0]); } else if (type instanceof Class) { return (Class<? extends SType>) type; } else {
throw new EthDroidException("type not handled (" + type.toString() + ")");
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SBytes.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // }
import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException;
package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 16/08/16. */ public class SBytes extends SType<Byte[]> { private SBytes(Byte[] value) { super(value); } public static SBytes fromByteArray(Byte[] value) { if (value.length > 32) {
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/exception/EthDroidException.java // public class EthDroidException extends RuntimeException { // // public EthDroidException(Exception e) { // super(e.getMessage(), e.getCause()); // } // // public EthDroidException(String message) { // super(message); // } // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SBytes.java import java.util.regex.Pattern; import io.ethmobile.ethdroid.exception.EthDroidException; package io.ethmobile.ethdroid.solidity.types; /** * Created by gunicolas on 16/08/16. */ public class SBytes extends SType<Byte[]> { private SBytes(Byte[] value) { super(value); } public static SBytes fromByteArray(Byte[] value) { if (value.length > 32) {
throw new EthDroidException("illegal argument. SBytes is limited to 32 bytes length.");
ethmobile/ethdroid
ethdroid/src/androidTest/java/io/ethmobile/ethdroid/EthDroidBuilderTest.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // }
import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File;
package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ public class EthDroidBuilderTest { private Context appContext; private String datadir; private EthDroid ethdroid; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); datadir = appContext.getFilesDir().getAbsolutePath();
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/Utils.java // public static void deleteDirIfExists(File file) { // File[] contents = file.listFiles(); // if (contents != null) { // for (File f : contents) { // deleteDirIfExists(f); // } // } // file.delete(); // } // Path: ethdroid/src/androidTest/java/io/ethmobile/ethdroid/EthDroidBuilderTest.java import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static io.ethmobile.ethdroid.Utils.deleteDirIfExists; import android.content.Context; import android.support.test.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; package io.ethmobile.ethdroid; /** * Created by gunicolas on 16/05/17. */ public class EthDroidBuilderTest { private Context appContext; private String datadir; private EthDroid ethdroid; @Before public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); datadir = appContext.getFilesDir().getAbsolutePath();
deleteDirIfExists(new File(datadir + "/GethDroid"));
ethmobile/ethdroid
ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/coder/decoder/SBoolDecoder.java
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SBool.java // public class SBool extends SType<Boolean> { // // private SBool(boolean value) { // super(value); // } // // public static SBool fromBoolean(boolean value) { // return new SBool(value); // } // // public static boolean isType(String name) { // return Pattern.compile("^bool(\\[([0-9])*\\])*$").matcher(name).matches(); // } // // @Override // public String asString() { // return value ? "1" : "0"; // } // // } // // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SType.java // public abstract class SType<T> { // // public static int ENCODED_SIZE = 64; // T value; // // public SType(T value) { // this.value = value; // } // // public static Class<? extends SType> getClazz() { // return SType.class; // } // // public final T get() { // return value; // } // // public abstract String asString(); // // @Override // public boolean equals(Object o) { // if (!(o instanceof SType)) return false; // SType toCompare = (SType) o; // return get().equals(toCompare.get()); // } // }
import io.ethmobile.ethdroid.solidity.types.SBool; import io.ethmobile.ethdroid.solidity.types.SType;
package io.ethmobile.ethdroid.solidity.coder.decoder; /** * Created by gunicolas on 06/02/17. */ public class SBoolDecoder implements SDecoder<SBool> { @Override public SBool decode(String toDecode) {
// Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SBool.java // public class SBool extends SType<Boolean> { // // private SBool(boolean value) { // super(value); // } // // public static SBool fromBoolean(boolean value) { // return new SBool(value); // } // // public static boolean isType(String name) { // return Pattern.compile("^bool(\\[([0-9])*\\])*$").matcher(name).matches(); // } // // @Override // public String asString() { // return value ? "1" : "0"; // } // // } // // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/types/SType.java // public abstract class SType<T> { // // public static int ENCODED_SIZE = 64; // T value; // // public SType(T value) { // this.value = value; // } // // public static Class<? extends SType> getClazz() { // return SType.class; // } // // public final T get() { // return value; // } // // public abstract String asString(); // // @Override // public boolean equals(Object o) { // if (!(o instanceof SType)) return false; // SType toCompare = (SType) o; // return get().equals(toCompare.get()); // } // } // Path: ethdroid/src/main/java/io/ethmobile/ethdroid/solidity/coder/decoder/SBoolDecoder.java import io.ethmobile.ethdroid.solidity.types.SBool; import io.ethmobile.ethdroid.solidity.types.SType; package io.ethmobile.ethdroid.solidity.coder.decoder; /** * Created by gunicolas on 06/02/17. */ public class SBoolDecoder implements SDecoder<SBool> { @Override public SBool decode(String toDecode) {
boolean value = toDecode.toCharArray()[SType.ENCODED_SIZE - 1] == '1';
ailab-uniud/distiller-CORE
src/main/java/it/uniud/ailab/dcore/persistence/Gram.java
// Path: src/main/java/it/uniud/ailab/dcore/annotation/Annotable.java // public abstract class Annotable { // // /** // * The list of annotation. // */ // private final Map<String,Annotation> annotations = new HashMap<>(); // // /** // * The identifier or the annotated object. // */ // private final String identifier; // // /** // * Generate an Annotable object. // * // * @param identifier the identifier of the object. // */ // protected Annotable(String identifier) { // this.identifier = identifier; // } // // /** // * Get the identifier of the object. // * // * @return the identifier of the object. // */ // public String getIdentifier() { // return identifier; // } // // /** // * Adds an annotation to the object. If there's an annotation with the same // * identifier, it will be overwritten. // * // * @param ann the annotation to add. // */ // public void addAnnotation(Annotation ann) { // annotations.put(ann.getAnnotator(),ann); // } // // /** // * Get the annotation specified with the specified annotator. // * // * @param annotator the annotator to search // * @return the annotation requested, {@code null} if not found. // */ // public Annotation getAnnotation(String annotator) { // return annotations.get(annotator); // } // // /** // * Get all the annotations stored in the object. // * // * @return all the annotations. // */ // public Annotation[] getAnnotations() { // return annotations.values().toArray(new Annotation[annotations.size()]); // } // // /** // * Check if the Annotable contains the specified annotation. // * // * @param annotator the identifier of the annotation to search // * @return true if the annotator has been annotated by the // * annotator provided as input, false otherwise. // */ // public boolean hasAnnotation(String annotator) { // return annotations.containsKey(annotator); // } // } // // Path: src/main/java/it/uniud/ailab/dcore/utils/ListUtils.java // public class ListUtils { // // /** // * Return the most common element in a list. If there are two or more // * most common elements in a list, return the first one encountered. // * // * @param <T> the type of the elements of the list // * @param list the list to analyze // * @return the most common element // */ // public static <T> T mostCommon(List<T> list) { // Map<T, Integer> map = new HashMap<>(); // // for (T t : list) { // Integer val = map.get(t); // map.put(t, val == null ? 1 : val + 1); // } // // Entry<T, Integer> max = null; // // for (Entry<T, Integer> e : map.entrySet()) { // if (max == null || e.getValue() > max.getValue()) { // max = e; // } // } // // return max == null? null : max.getKey(); // } // // }
import com.fasterxml.jackson.annotation.JsonIgnore; import it.uniud.ailab.dcore.annotation.Annotable; import it.uniud.ailab.dcore.utils.ListUtils; import java.util.ArrayList; import java.util.List;
*/ public void addSurfaces(List<String> surfaces,List<List<Token>> tokenLists) { if (surfaces.size() != tokenLists.size()) throw new IllegalArgumentException( "Mismatching size of surfaces and token lists."); this.surfaces.addAll(surfaces); // note: do not use addAll. The references are lost if you don't copy for (List<Token> t : tokenLists) { this.tokenLists.add(new ArrayList<Token>(t)); } } /** * Get the type of the Gram that depends on the type of Gram implementation. * * @return the type of gram. */ public String getType(){ return type; } /** * The tokens that form the most common surface of the gram. * * @return the tokens of the surface of the gram. */ public List<Token> getTokens() {
// Path: src/main/java/it/uniud/ailab/dcore/annotation/Annotable.java // public abstract class Annotable { // // /** // * The list of annotation. // */ // private final Map<String,Annotation> annotations = new HashMap<>(); // // /** // * The identifier or the annotated object. // */ // private final String identifier; // // /** // * Generate an Annotable object. // * // * @param identifier the identifier of the object. // */ // protected Annotable(String identifier) { // this.identifier = identifier; // } // // /** // * Get the identifier of the object. // * // * @return the identifier of the object. // */ // public String getIdentifier() { // return identifier; // } // // /** // * Adds an annotation to the object. If there's an annotation with the same // * identifier, it will be overwritten. // * // * @param ann the annotation to add. // */ // public void addAnnotation(Annotation ann) { // annotations.put(ann.getAnnotator(),ann); // } // // /** // * Get the annotation specified with the specified annotator. // * // * @param annotator the annotator to search // * @return the annotation requested, {@code null} if not found. // */ // public Annotation getAnnotation(String annotator) { // return annotations.get(annotator); // } // // /** // * Get all the annotations stored in the object. // * // * @return all the annotations. // */ // public Annotation[] getAnnotations() { // return annotations.values().toArray(new Annotation[annotations.size()]); // } // // /** // * Check if the Annotable contains the specified annotation. // * // * @param annotator the identifier of the annotation to search // * @return true if the annotator has been annotated by the // * annotator provided as input, false otherwise. // */ // public boolean hasAnnotation(String annotator) { // return annotations.containsKey(annotator); // } // } // // Path: src/main/java/it/uniud/ailab/dcore/utils/ListUtils.java // public class ListUtils { // // /** // * Return the most common element in a list. If there are two or more // * most common elements in a list, return the first one encountered. // * // * @param <T> the type of the elements of the list // * @param list the list to analyze // * @return the most common element // */ // public static <T> T mostCommon(List<T> list) { // Map<T, Integer> map = new HashMap<>(); // // for (T t : list) { // Integer val = map.get(t); // map.put(t, val == null ? 1 : val + 1); // } // // Entry<T, Integer> max = null; // // for (Entry<T, Integer> e : map.entrySet()) { // if (max == null || e.getValue() > max.getValue()) { // max = e; // } // } // // return max == null? null : max.getKey(); // } // // } // Path: src/main/java/it/uniud/ailab/dcore/persistence/Gram.java import com.fasterxml.jackson.annotation.JsonIgnore; import it.uniud.ailab.dcore.annotation.Annotable; import it.uniud.ailab.dcore.utils.ListUtils; import java.util.ArrayList; import java.util.List; */ public void addSurfaces(List<String> surfaces,List<List<Token>> tokenLists) { if (surfaces.size() != tokenLists.size()) throw new IllegalArgumentException( "Mismatching size of surfaces and token lists."); this.surfaces.addAll(surfaces); // note: do not use addAll. The references are lost if you don't copy for (List<Token> t : tokenLists) { this.tokenLists.add(new ArrayList<Token>(t)); } } /** * Get the type of the Gram that depends on the type of Gram implementation. * * @return the type of gram. */ public String getType(){ return type; } /** * The tokens that form the most common surface of the gram. * * @return the tokens of the surface of the gram. */ public List<Token> getTokens() {
return tokenLists.get(surfaces.indexOf(ListUtils.mostCommon(surfaces)));
jhclark/bigfatlm
src/bigfat/step5/InterpolateOrdersInfo.java
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import bigfat.util.SerializationPrecision;
package bigfat.step5; /** * @author jhclark */ public class InterpolateOrdersInfo implements Writable { private double p; private double bo; public double getInterpolatedProb() { return p; } public double getBackoffWeight() { return bo; } public void setInfo(double p, double bo) { this.bo = bo; this.p = p; } @Override public void write(DataOutput out) throws IOException {
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/step5/InterpolateOrdersInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import bigfat.util.SerializationPrecision; package bigfat.step5; /** * @author jhclark */ public class InterpolateOrdersInfo implements Writable { private double p; private double bo; public double getInterpolatedProb() { return p; } public double getBackoffWeight() { return bo; } public void setInfo(double p, double bo) { this.bo = bo; this.p = p; } @Override public void write(DataOutput out) throws IOException {
SerializationPrecision.writeReal(out, p);
jhclark/bigfatlm
src/bigfat/step1/VocabMapper.java
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // }
import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Mapper; import bigfat.BigFatLM;
package bigfat.step1; public class VocabMapper extends Mapper<LongWritable, Text, Text, LongWritable> { private final static LongWritable ONE = new LongWritable(1); private Text word = new Text(); private Counter sentCount; private Counter tokenCount; @Override public void setup(Context context) {
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // } // Path: src/bigfat/step1/VocabMapper.java import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Mapper; import bigfat.BigFatLM; package bigfat.step1; public class VocabMapper extends Mapper<LongWritable, Text, Text, LongWritable> { private final static LongWritable ONE = new LongWritable(1); private Text word = new Text(); private Counter sentCount; private Counter tokenCount; @Override public void setup(Context context) {
this.sentCount = context.getCounter(BigFatLM.PROGRAM_NAME, "Sentences");
jhclark/bigfatlm
src/bigfat/step5/InterpolateOrdersIntermediateInfo.java
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import bigfat.util.SerializationPrecision;
package bigfat.step5; /** * A convenience wrapper for count of counts keys * * @author jon * */ public class InterpolateOrdersIntermediateInfo implements Writable { private double prob; private double interpWeight; public double getUninterpolatedProb() { return prob; } public double getInterpolationWeight() { return interpWeight; } public void setValues(double p, double interpWeight) { this.prob = p; this.interpWeight = interpWeight; } @Override public void write(DataOutput out) throws IOException {
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/step5/InterpolateOrdersIntermediateInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import bigfat.util.SerializationPrecision; package bigfat.step5; /** * A convenience wrapper for count of counts keys * * @author jon * */ public class InterpolateOrdersIntermediateInfo implements Writable { private double prob; private double interpWeight; public double getUninterpolatedProb() { return prob; } public double getInterpolationWeight() { return interpWeight; } public void setValues(double p, double interpWeight) { this.prob = p; this.interpWeight = interpWeight; } @Override public void write(DataOutput out) throws IOException {
SerializationPrecision.writeReal(out, prob);
jhclark/bigfatlm
src/bigfat/step6/RenormalizeBackoffsInfo.java
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.Ngram; import bigfat.util.SerializationPrecision;
package bigfat.step6; /** * * @author jhclark * */ public class RenormalizeBackoffsInfo implements Writable, Serializable { private static final long serialVersionUID = 2846558896011479855L; private int word; private double prob; private RenormalizeBackoffsInfo(RenormalizeBackoffsInfo other) { this.prob = other.prob; this.word = other.word; } public RenormalizeBackoffsInfo() { } public RenormalizeBackoffsInfo copy() { return new RenormalizeBackoffsInfo(this); } // custom java Serialization just defers to custom Hadoop serialization private void writeObject(ObjectOutputStream out) throws IOException { write(out); } // custom java Serialization just defers to custom Hadoop serialization private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readFields(in); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, word);
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/step6/RenormalizeBackoffsInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.Ngram; import bigfat.util.SerializationPrecision; package bigfat.step6; /** * * @author jhclark * */ public class RenormalizeBackoffsInfo implements Writable, Serializable { private static final long serialVersionUID = 2846558896011479855L; private int word; private double prob; private RenormalizeBackoffsInfo(RenormalizeBackoffsInfo other) { this.prob = other.prob; this.word = other.word; } public RenormalizeBackoffsInfo() { } public RenormalizeBackoffsInfo copy() { return new RenormalizeBackoffsInfo(this); } // custom java Serialization just defers to custom Hadoop serialization private void writeObject(ObjectOutputStream out) throws IOException { write(out); } // custom java Serialization just defers to custom Hadoop serialization private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readFields(in); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, word);
SerializationPrecision.writeReal(out, prob);
jhclark/bigfatlm
src/bigfat/step6/RenormalizeBackoffsInfo.java
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.Ngram; import bigfat.util.SerializationPrecision;
readFields(in); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, word); SerializationPrecision.writeReal(out, prob); } @Override public void readFields(DataInput in) throws IOException { this.word = WritableUtils.readVInt(in); this.prob = SerializationPrecision.readReal(in); } public double getProb() { return prob; } public int getWord() { return word; } public void setInfo(int wordId, double p) { this.prob = p; this.word = wordId; } @Override public String toString() {
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/step6/RenormalizeBackoffsInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.Ngram; import bigfat.util.SerializationPrecision; readFields(in); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, word); SerializationPrecision.writeReal(out, prob); } @Override public void readFields(DataInput in) throws IOException { this.word = WritableUtils.readVInt(in); this.prob = SerializationPrecision.readReal(in); } public double getProb() { return prob; } public int getWord() { return word; } public void setInfo(int wordId, double p) { this.prob = p; this.word = wordId; } @Override public String toString() {
if(Ngram.DEBUG_VOCAB == null) {
jhclark/bigfatlm
src/bigfat/step6/RenormalizeBackoffsSortComparator.java
// Path: src/bigfat/datastructs/NgramComparator.java // public class NgramComparator extends WritableComparator { // public NgramComparator() { // super(Ngram.class); // } // // public int compare(byte[] buf1, int start1, int len1, byte[] buf2, // int start2, int len2) { // // return compareNgramsRaw(buf1, start1, buf2, start2); // } // // public static int compareNgramsRaw(byte[] buf1, int start1, byte[] buf2, // int start2) { // // try { // // determine order of ngrams (size of lists) // int size1 = readVInt(buf1, start1); // int size2 = readVInt(buf2, start2); // // // skip over list sizes // int curWordOffset1 = WritableUtils.decodeVIntSize(buf1[start1]) // + start1; // int curWordOffset2 = WritableUtils.decodeVIntSize(buf2[start2]) // + start2; // // for (int i = 0; i < size1 || i < size2; i++) { // if (i >= size1) { // // equal up to this point, but 2 is longer -- we're in // // order // return -1; // } else if (i >= size2) { // // equal up to this point, but 1 is longer -- swap so that 1 // // comes after 2 // return 1; // } // // TODO: Zeros come first! // int wordSize1 = WritableUtils // .decodeVIntSize(buf1[curWordOffset1]); // int wordSize2 = WritableUtils // .decodeVIntSize(buf2[curWordOffset2]); // int resultAtI = compareBytes(buf1, curWordOffset1, // wordSize1, buf2, curWordOffset2, wordSize2); // if (resultAtI != 0) { // return resultAtI; // } // curWordOffset1 += wordSize1; // curWordOffset2 += wordSize2; // } // // same length, same content // // (we would have detected 2 longer than 1 in the loop) // return 0; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import java.io.IOException; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.NgramComparator;
package bigfat.step6; public class RenormalizeBackoffsSortComparator extends WritableComparator { public RenormalizeBackoffsSortComparator() { super(RenormalizeBackoffsKey.class); } public int compare(byte[] buf1, int start1, int len1, byte[] buf2, int start2, int len2) { try { int order1 = readVInt(buf1, start1); int order2 = readVInt(buf2, start2); int result; if (order1 < order2) { result = -1; // in order } else if (order1 > order2) { result = 1; // flip } else { int ngramStart1 = WritableUtils.decodeVIntSize(buf1[start1]) + start1; int ngramStart2 = WritableUtils.decodeVIntSize(buf2[start2]) + start2;
// Path: src/bigfat/datastructs/NgramComparator.java // public class NgramComparator extends WritableComparator { // public NgramComparator() { // super(Ngram.class); // } // // public int compare(byte[] buf1, int start1, int len1, byte[] buf2, // int start2, int len2) { // // return compareNgramsRaw(buf1, start1, buf2, start2); // } // // public static int compareNgramsRaw(byte[] buf1, int start1, byte[] buf2, // int start2) { // // try { // // determine order of ngrams (size of lists) // int size1 = readVInt(buf1, start1); // int size2 = readVInt(buf2, start2); // // // skip over list sizes // int curWordOffset1 = WritableUtils.decodeVIntSize(buf1[start1]) // + start1; // int curWordOffset2 = WritableUtils.decodeVIntSize(buf2[start2]) // + start2; // // for (int i = 0; i < size1 || i < size2; i++) { // if (i >= size1) { // // equal up to this point, but 2 is longer -- we're in // // order // return -1; // } else if (i >= size2) { // // equal up to this point, but 1 is longer -- swap so that 1 // // comes after 2 // return 1; // } // // TODO: Zeros come first! // int wordSize1 = WritableUtils // .decodeVIntSize(buf1[curWordOffset1]); // int wordSize2 = WritableUtils // .decodeVIntSize(buf2[curWordOffset2]); // int resultAtI = compareBytes(buf1, curWordOffset1, // wordSize1, buf2, curWordOffset2, wordSize2); // if (resultAtI != 0) { // return resultAtI; // } // curWordOffset1 += wordSize1; // curWordOffset2 += wordSize2; // } // // same length, same content // // (we would have detected 2 longer than 1 in the loop) // return 0; // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/bigfat/step6/RenormalizeBackoffsSortComparator.java import java.io.IOException; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.WritableUtils; import bigfat.datastructs.NgramComparator; package bigfat.step6; public class RenormalizeBackoffsSortComparator extends WritableComparator { public RenormalizeBackoffsSortComparator() { super(RenormalizeBackoffsKey.class); } public int compare(byte[] buf1, int start1, int len1, byte[] buf2, int start2, int len2) { try { int order1 = readVInt(buf1, start1); int order2 = readVInt(buf2, start2); int result; if (order1 < order2) { result = -1; // in order } else if (order1 > order2) { result = 1; // flip } else { int ngramStart1 = WritableUtils.decodeVIntSize(buf1[start1]) + start1; int ngramStart2 = WritableUtils.decodeVIntSize(buf2[start2]) + start2;
int ngramResult = NgramComparator.compareNgramsRaw(buf1,
jhclark/bigfatlm
src/bigfat/interpolate/ARPALanguageModel.java
// Path: src/bigfat/util/StringUtils.java // public class StringUtils { // // public static String[] tokenize(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // String[] toks = new String[tok.countTokens()]; // for (int i = 0; i < toks.length; i++) { // toks[i] = tok.nextToken(); // } // return toks; // } // // public static int count(String ngram, char c) { // int n = 0; // for (int i = 0; i < ngram.length(); i++) { // if (ngram.charAt(i) == c) { // n++; // } // } // return n; // } // // public static String getSubstringBefore(String str, char c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(0, i); // } // // public static String getSubstringAfterLast(String str, char c) { // int i = str.lastIndexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i+1); // } // // public static String getSubstringAfter(String str, String c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i + c.length()); // } // // public static List<String> tokenizeList(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // int numToks = tok.countTokens(); // List<String> toks = new ArrayList<String>(numToks); // for (int i = 0; i < numToks; i++) { // toks.add(tok.nextToken()); // } // return toks; // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import bigfat.util.StringUtils;
private double unkLogProb; public void load(File f, boolean readRawFormat) throws IOException { BufferedReader in = new BufferedReader(new FileReader(f)); if (readRawFormat) { readRawFormat(in); } else { readArpa(in); } if (table == null) { throw new RuntimeException("No entries for LM " + f.getAbsolutePath()); } LMEntry unkEntry = table.get(0).get(Collections.singletonList("<unk>")); if (unkEntry == null) { throw new RuntimeException("<unk> entry not found."); } this.unkLogProb = unkEntry.logProb; } private void readRawFormat(BufferedReader in) throws NumberFormatException, IOException { table = new ArrayList<Map<List<String>, LMEntry>>(); String line; while ((line = in.readLine()) != null) {
// Path: src/bigfat/util/StringUtils.java // public class StringUtils { // // public static String[] tokenize(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // String[] toks = new String[tok.countTokens()]; // for (int i = 0; i < toks.length; i++) { // toks[i] = tok.nextToken(); // } // return toks; // } // // public static int count(String ngram, char c) { // int n = 0; // for (int i = 0; i < ngram.length(); i++) { // if (ngram.charAt(i) == c) { // n++; // } // } // return n; // } // // public static String getSubstringBefore(String str, char c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(0, i); // } // // public static String getSubstringAfterLast(String str, char c) { // int i = str.lastIndexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i+1); // } // // public static String getSubstringAfter(String str, String c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i + c.length()); // } // // public static List<String> tokenizeList(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // int numToks = tok.countTokens(); // List<String> toks = new ArrayList<String>(numToks); // for (int i = 0; i < numToks; i++) { // toks.add(tok.nextToken()); // } // return toks; // } // } // Path: src/bigfat/interpolate/ARPALanguageModel.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import bigfat.util.StringUtils; private double unkLogProb; public void load(File f, boolean readRawFormat) throws IOException { BufferedReader in = new BufferedReader(new FileReader(f)); if (readRawFormat) { readRawFormat(in); } else { readArpa(in); } if (table == null) { throw new RuntimeException("No entries for LM " + f.getAbsolutePath()); } LMEntry unkEntry = table.get(0).get(Collections.singletonList("<unk>")); if (unkEntry == null) { throw new RuntimeException("<unk> entry not found."); } this.unkLogProb = unkEntry.logProb; } private void readRawFormat(BufferedReader in) throws NumberFormatException, IOException { table = new ArrayList<Map<List<String>, LMEntry>>(); String line; while ((line = in.readLine()) != null) {
String[] columns = StringUtils.tokenize(line, "\t");
jhclark/bigfatlm
src/bigfat/step3/Discounts.java
// Path: src/bigfat/util/StringUtils.java // public class StringUtils { // // public static String[] tokenize(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // String[] toks = new String[tok.countTokens()]; // for (int i = 0; i < toks.length; i++) { // toks[i] = tok.nextToken(); // } // return toks; // } // // public static int count(String ngram, char c) { // int n = 0; // for (int i = 0; i < ngram.length(); i++) { // if (ngram.charAt(i) == c) { // n++; // } // } // return n; // } // // public static String getSubstringBefore(String str, char c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(0, i); // } // // public static String getSubstringAfterLast(String str, char c) { // int i = str.lastIndexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i+1); // } // // public static String getSubstringAfter(String str, String c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i + c.length()); // } // // public static List<String> tokenizeList(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // int numToks = tok.countTokens(); // List<String> toks = new ArrayList<String>(numToks); // for (int i = 0; i < numToks; i++) { // toks.add(tok.nextToken()); // } // return toks; // } // }
import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import bigfat.util.StringUtils;
package bigfat.step3; public class Discounts { double[][] discountTable; public double getDiscount(int order, int count) { if (count == 0 || order == 0) { return 0; } else { return discountTable[order - 1][count - 1]; } } public static Discounts load(BufferedReader in) throws IOException { Discounts d = new Discounts(); int maxOrder = 0; int maxCount = 0; List<String> lines = new ArrayList<String>(100); { String line; while ((line = in.readLine()) != null) {
// Path: src/bigfat/util/StringUtils.java // public class StringUtils { // // public static String[] tokenize(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // String[] toks = new String[tok.countTokens()]; // for (int i = 0; i < toks.length; i++) { // toks[i] = tok.nextToken(); // } // return toks; // } // // public static int count(String ngram, char c) { // int n = 0; // for (int i = 0; i < ngram.length(); i++) { // if (ngram.charAt(i) == c) { // n++; // } // } // return n; // } // // public static String getSubstringBefore(String str, char c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(0, i); // } // // public static String getSubstringAfterLast(String str, char c) { // int i = str.lastIndexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i+1); // } // // public static String getSubstringAfter(String str, String c) { // int i = str.indexOf(c); // if(i == -1) { // throw new RuntimeException(c + " not found in " + str); // } // return str.substring(i + c.length()); // } // // public static List<String> tokenizeList(String str, String delims) { // StringTokenizer tok = new StringTokenizer(str, delims); // int numToks = tok.countTokens(); // List<String> toks = new ArrayList<String>(numToks); // for (int i = 0; i < numToks; i++) { // toks.add(tok.nextToken()); // } // return toks; // } // } // Path: src/bigfat/step3/Discounts.java import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import bigfat.util.StringUtils; package bigfat.step3; public class Discounts { double[][] discountTable; public double getDiscount(int order, int count) { if (count == 0 || order == 0) { return 0; } else { return discountTable[order - 1][count - 1]; } } public static Discounts load(BufferedReader in) throws IOException { Discounts d = new Discounts(); int maxOrder = 0; int maxCount = 0; List<String> lines = new ArrayList<String>(100); { String line; while ((line = in.readLine()) != null) {
String[] toks = StringUtils.tokenize(line, "\t");
jhclark/bigfatlm
src/bigfat/DataViewer.java
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/step1/Vocabulary.java // public class Vocabulary { // // private final String[] vocab; // // private Vocabulary(int size) { // this.vocab = new String[size]; // } // // public String toWord(int i) { // if(i == BigFatLM.ZEROTON_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.UNK_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.BOS_ID) { // return BigFatLM.BOS; // } else if (i == BigFatLM.EOS_ID) { // return BigFatLM.EOS; // } else { // return vocab[i-1]; // } // } // // public static Vocabulary load(Path vocabFile, FileSystem fs) throws IOException { // // BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // int size = 0; // String line; // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // int n = Integer.parseInt(columns[1]); // if (n > 0) { // size++; // } // } // in.close(); // // in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // Vocabulary v = new Vocabulary(size); // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // String tok = columns[0]; // int n = Integer.parseInt(columns[1]); // if (n > 0) { // v.vocab[n-1] = tok; // } // } // in.close(); // return v; // } // }
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import bigfat.datastructs.Ngram; import bigfat.step1.Vocabulary;
package bigfat; public class DataViewer { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); Path dataPath = new Path(args[0]); FileSystem fs = dataPath.getFileSystem(conf); SequenceFile.Reader read = new SequenceFile.Reader(fs, dataPath, conf); if(args.length == 2) { Path vocabPath = new Path(args[1]);
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/step1/Vocabulary.java // public class Vocabulary { // // private final String[] vocab; // // private Vocabulary(int size) { // this.vocab = new String[size]; // } // // public String toWord(int i) { // if(i == BigFatLM.ZEROTON_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.UNK_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.BOS_ID) { // return BigFatLM.BOS; // } else if (i == BigFatLM.EOS_ID) { // return BigFatLM.EOS; // } else { // return vocab[i-1]; // } // } // // public static Vocabulary load(Path vocabFile, FileSystem fs) throws IOException { // // BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // int size = 0; // String line; // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // int n = Integer.parseInt(columns[1]); // if (n > 0) { // size++; // } // } // in.close(); // // in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // Vocabulary v = new Vocabulary(size); // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // String tok = columns[0]; // int n = Integer.parseInt(columns[1]); // if (n > 0) { // v.vocab[n-1] = tok; // } // } // in.close(); // return v; // } // } // Path: src/bigfat/DataViewer.java import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import bigfat.datastructs.Ngram; import bigfat.step1.Vocabulary; package bigfat; public class DataViewer { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); Path dataPath = new Path(args[0]); FileSystem fs = dataPath.getFileSystem(conf); SequenceFile.Reader read = new SequenceFile.Reader(fs, dataPath, conf); if(args.length == 2) { Path vocabPath = new Path(args[1]);
Vocabulary vocab = Vocabulary.load(vocabPath, fs);
jhclark/bigfatlm
src/bigfat/DataViewer.java
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/step1/Vocabulary.java // public class Vocabulary { // // private final String[] vocab; // // private Vocabulary(int size) { // this.vocab = new String[size]; // } // // public String toWord(int i) { // if(i == BigFatLM.ZEROTON_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.UNK_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.BOS_ID) { // return BigFatLM.BOS; // } else if (i == BigFatLM.EOS_ID) { // return BigFatLM.EOS; // } else { // return vocab[i-1]; // } // } // // public static Vocabulary load(Path vocabFile, FileSystem fs) throws IOException { // // BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // int size = 0; // String line; // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // int n = Integer.parseInt(columns[1]); // if (n > 0) { // size++; // } // } // in.close(); // // in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // Vocabulary v = new Vocabulary(size); // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // String tok = columns[0]; // int n = Integer.parseInt(columns[1]); // if (n > 0) { // v.vocab[n-1] = tok; // } // } // in.close(); // return v; // } // }
import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import bigfat.datastructs.Ngram; import bigfat.step1.Vocabulary;
package bigfat; public class DataViewer { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); Path dataPath = new Path(args[0]); FileSystem fs = dataPath.getFileSystem(conf); SequenceFile.Reader read = new SequenceFile.Reader(fs, dataPath, conf); if(args.length == 2) { Path vocabPath = new Path(args[1]); Vocabulary vocab = Vocabulary.load(vocabPath, fs);
// Path: src/bigfat/datastructs/Ngram.java // public class Ngram implements WritableComparable<Ngram> { // // public static Vocabulary DEBUG_VOCAB = null; // public static void setVocabForDebug(Vocabulary vocab) { // DEBUG_VOCAB = vocab; // } // // public static final int DEFAULT_SIZE = 5; // private FastIntArrayList list = new FastIntArrayList(DEFAULT_SIZE); // // public int getOrder() { // if(list.size() == 1 && list.get(0) == BigFatLM.ZEROTON_ID) { // return 0; // } else { // return list.size(); // } // } // // @Override // public void write(DataOutput out) throws IOException { // SerializationUtils.writeList(out, list); // } // // @Override // public void readFields(DataInput in) throws IOException { // SerializationUtils.readList(in, list); // } // // @Override // public int compareTo(Ngram other) { // throw new RuntimeException("Use raw comparator instead."); // } // // static { // // register this comparator // WritableComparator.define(Ngram.class, new NgramComparator()); // } // // public void setFromIds(FastIntArrayList ids, boolean reverse) { // if (!reverse) { // this.list = ids; // } else { // this.list.clear(); // for (int i = ids.size() - 1; i >= 0; i--) { // this.list.add(ids.get(i)); // } // } // } // // public void getAsIds(FastIntArrayList ids) { // getAsIds(ids, false); // } // // public void getAsIds(FastIntArrayList ids, boolean reverse) { // ids.clear(); // if (!reverse) { // ids.addAll(list); // } else { // for (int i = list.size() - 1; i >= 0; i--) { // ids.add(list.get(i)); // } // } // } // // public String toString() { // if(DEBUG_VOCAB == null) { // return list.toString(); // } else { // StringBuilder builder = new StringBuilder(); // DArpaMapper.stringify(list, DEBUG_VOCAB, builder); // return builder.toString(); // } // } // } // // Path: src/bigfat/step1/Vocabulary.java // public class Vocabulary { // // private final String[] vocab; // // private Vocabulary(int size) { // this.vocab = new String[size]; // } // // public String toWord(int i) { // if(i == BigFatLM.ZEROTON_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.UNK_ID) { // return BigFatLM.UNK; // } else if (i == BigFatLM.BOS_ID) { // return BigFatLM.BOS; // } else if (i == BigFatLM.EOS_ID) { // return BigFatLM.EOS; // } else { // return vocab[i-1]; // } // } // // public static Vocabulary load(Path vocabFile, FileSystem fs) throws IOException { // // BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // int size = 0; // String line; // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // int n = Integer.parseInt(columns[1]); // if (n > 0) { // size++; // } // } // in.close(); // // in = new BufferedReader(new InputStreamReader(fs.open(vocabFile))); // Vocabulary v = new Vocabulary(size); // while ((line = in.readLine()) != null) { // String[] columns = StringUtils.tokenize(line, "\t"); // String tok = columns[0]; // int n = Integer.parseInt(columns[1]); // if (n > 0) { // v.vocab[n-1] = tok; // } // } // in.close(); // return v; // } // } // Path: src/bigfat/DataViewer.java import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import bigfat.datastructs.Ngram; import bigfat.step1.Vocabulary; package bigfat; public class DataViewer { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); Path dataPath = new Path(args[0]); FileSystem fs = dataPath.getFileSystem(conf); SequenceFile.Reader read = new SequenceFile.Reader(fs, dataPath, conf); if(args.length == 2) { Path vocabPath = new Path(args[1]); Vocabulary vocab = Vocabulary.load(vocabPath, fs);
Ngram.setVocabForDebug(vocab);
jhclark/bigfatlm
src/bigfat/step1/VocabReducer.java
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // }
import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Reducer; import bigfat.BigFatLM;
package bigfat.step1; public class VocabReducer extends Reducer<Text, LongWritable, Text, LongWritable> { private LongWritable writable = new LongWritable(); private Counter typeCount; @Override public void setup(Context context) {
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // } // Path: src/bigfat/step1/VocabReducer.java import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Reducer; import bigfat.BigFatLM; package bigfat.step1; public class VocabReducer extends Reducer<Text, LongWritable, Text, LongWritable> { private LongWritable writable = new LongWritable(); private Counter typeCount; @Override public void setup(Context context) {
this.typeCount = context.getCounter(BigFatLM.PROGRAM_NAME, "Types");
jhclark/bigfatlm
src/bigfat/interpolate/step2/InterpolateModelsVector.java
// Path: src/bigfat/datastructs/SerializationUtils.java // public class SerializationUtils { // // public static void writeList(DataOutput out, FastIntArrayList list) throws IOException { // WritableUtils.writeVInt(out, list.size()); // for (int i = 0; i < list.size(); i++) { // WritableUtils.writeVInt(out, list.get(i)); // } // } // // public static void readList(DataInput in, FastIntArrayList list) throws IOException { // list.clear(); // int size = WritableUtils.readVInt(in); // for (int i = 0; i < size; i++) { // list.add(WritableUtils.readVInt(in)); // } // } // // public static void writeArray(DataOutput out, float[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // out.writeFloat(arr[i]); // } // } // // public static float[] readArray(DataInput in, float[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // float[] result; // if(arr == null || len != arr.length) { // result = new float[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = in.readFloat(); // } // return result; // } // // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.io.Writable; import bigfat.datastructs.SerializationUtils; import bigfat.util.SerializationPrecision;
package bigfat.interpolate.step2; /** * @author jhclark */ public class InterpolateModelsVector implements Writable { private double[] p; private double[] bo; public double[] getProbs() { return p; } public double[] getBackoffWeights() { return bo; } public void setInfo(double[] p, double[] bo) { this.bo = bo; this.p = p; } @Override public void write(DataOutput out) throws IOException {
// Path: src/bigfat/datastructs/SerializationUtils.java // public class SerializationUtils { // // public static void writeList(DataOutput out, FastIntArrayList list) throws IOException { // WritableUtils.writeVInt(out, list.size()); // for (int i = 0; i < list.size(); i++) { // WritableUtils.writeVInt(out, list.get(i)); // } // } // // public static void readList(DataInput in, FastIntArrayList list) throws IOException { // list.clear(); // int size = WritableUtils.readVInt(in); // for (int i = 0; i < size; i++) { // list.add(WritableUtils.readVInt(in)); // } // } // // public static void writeArray(DataOutput out, float[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // out.writeFloat(arr[i]); // } // } // // public static float[] readArray(DataInput in, float[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // float[] result; // if(arr == null || len != arr.length) { // result = new float[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = in.readFloat(); // } // return result; // } // // } // // Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/interpolate/step2/InterpolateModelsVector.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import org.apache.hadoop.io.Writable; import bigfat.datastructs.SerializationUtils; import bigfat.util.SerializationPrecision; package bigfat.interpolate.step2; /** * @author jhclark */ public class InterpolateModelsVector implements Writable { private double[] p; private double[] bo; public double[] getProbs() { return p; } public double[] getBackoffWeights() { return bo; } public void setInfo(double[] p, double[] bo) { this.bo = bo; this.p = p; } @Override public void write(DataOutput out) throws IOException {
SerializationPrecision.writeRealArray(out, p);
jhclark/bigfatlm
src/bigfat/interpolate/step1/InterpolateModelsInfo.java
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // }
import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.util.SerializationPrecision;
public double getBackoffWeight() { return bo; } public int getModelNumber() { return modelNumber; } public void setAllInfo(int modelNumber, double p, double bo) { this.modelNumber = modelNumber; this.bo = bo; this.p = p; } public void setProbInfo(int modelNumber, double p) { this.modelNumber = modelNumber; this.bo = Double.NEGATIVE_INFINITY; this.p = p; } public void setBackoffInfo(int modelNumber, double bo) { this.modelNumber = modelNumber; this.bo = bo; this.p = Double.NEGATIVE_INFINITY; } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, modelNumber);
// Path: src/bigfat/util/SerializationPrecision.java // public class SerializationPrecision { // public static boolean DOUBLE_PRECISION = false; // // public static void writeReal(DataOutput out, double prob) throws IOException { // if(DOUBLE_PRECISION) { // out.writeDouble(prob); // } else { // out.writeFloat((float)prob); // } // } // // public static double readReal(DataInput in) throws IOException { // if(DOUBLE_PRECISION) { // return in.readDouble(); // } else { // return in.readFloat(); // } // } // // public static void writeRealArray(DataOutput out, double[] arr) throws IOException { // WritableUtils.writeVInt(out, arr.length); // for(int i=0; i<arr.length; i++) { // writeReal(out, arr[i]); // } // } // // public static double[] readRealArray(DataInput in, double[] arr) throws IOException { // int len = WritableUtils.readVInt(in); // double[] result; // if(arr == null || len != arr.length) { // result = new double[len]; // } else { // result = arr; // } // for(int i=0; i<len; i++) { // result[i] = readReal(in); // } // return result; // } // } // Path: src/bigfat/interpolate/step1/InterpolateModelsInfo.java import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableUtils; import bigfat.util.SerializationPrecision; public double getBackoffWeight() { return bo; } public int getModelNumber() { return modelNumber; } public void setAllInfo(int modelNumber, double p, double bo) { this.modelNumber = modelNumber; this.bo = bo; this.p = p; } public void setProbInfo(int modelNumber, double p) { this.modelNumber = modelNumber; this.bo = Double.NEGATIVE_INFINITY; this.p = p; } public void setBackoffInfo(int modelNumber, double bo) { this.modelNumber = modelNumber; this.bo = bo; this.p = Double.NEGATIVE_INFINITY; } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeVInt(out, modelNumber);
SerializationPrecision.writeReal(out, p);
jhclark/bigfatlm
src/bigfat/datastructs/FastIntArrayList.java
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // }
import java.util.concurrent.atomic.AtomicInteger; import bigfat.BigFatLM;
sub.globalRevision = this.globalRevision; sub.mutable = false; } // TODO: Check bounds? sub.data = this.data; sub.start = this.start + i; sub.end = this.start + j; return sub; } public void clear() { start = 0; end = 0; if (PARANOID) { myRevision = globalRevision.incrementAndGet(); } } // ZEROTON_ID is assumed to come first // TODO: Move this compareTo() to more specific location public int compareTo(FastIntArrayList other) { for (int i = 0; i < this.size() || i < other.size(); i++) { if (i >= this.size()) { return -1; } else if (i >= other.size()) { return 1; } else { int myId = this.get(i); int otherId = other.get(i); if (myId != otherId) {
// Path: src/bigfat/BigFatLM.java // public class BigFatLM extends Configured implements Tool { // // public static final String PROGRAM_NAME = "BigFatLM"; // public static final int ZEROTON_ID = 0; // public static final String UNK = "<unk>"; // public static final int UNK_ID = -1; // public static final String BOS = "<s>"; // public static final int BOS_ID = -2; // public static final String EOS = "</s>"; // public static final int EOS_ID = -3; // public static final float LOG_PROB_OF_ZERO = -99; // // @Option(shortName = "v", longName = "verbosity", usage = "Verbosity level", defaultValue = "0") // public static int verbosity; // // private static final ImmutableMap<String, HadoopIteration> modules = new ImmutableMap.Builder<String, HadoopIteration>() // .put("vocab", new VocabIteration()) // .put("extract", new ExtractIteration()) // .put("discounts", new DiscountsIteration()) // .put("uninterp", new UninterpolatedIteration()) // .put("interpOrders", new InterpolateOrdersIteration()) // .put("renorm", new RenormalizeBackoffsIteration()) // .put("darpa", new DArpaIteration()) // .put("filter", new ArpaFilterIteration()) // .put("mergearpa", new ArpaMergeIteration()) // .put("findModelInterpWeights", // new OptimizeInterpolateModelsIteration()) // .put("makeModelVectors", new AttachBackoffsIteration()) // .put("interpModels", new InterpolateModelsIteration()).build(); // // public int run(String[] args) throws Exception { // // if (args.length == 0 || !modules.keySet().contains(args[0])) { // System.err.println("Usage: program <module_name>"); // System.err.println("Available modules: " // + modules.keySet().toString()); // System.exit(1); // } else { // String moduleName = args[0]; // HadoopIteration module = modules.get(moduleName); // Configurator opts = new Configurator().withProgramHeader( // PROGRAM_NAME + " V0.1\nBy Jonathan Clark") // .withModuleOptions(moduleName, module.getClass()); // // for (Class<?> configurable : module.getConfigurables()) { // opts.withModuleOptions(moduleName, configurable); // } // // try { // opts.readFrom(args); // opts.configure(module); // } catch (ConfigurationException e) { // opts.printUsageTo(System.err); // System.err.println("ERROR: " + e.getMessage() + "\n"); // System.exit(1); // } // // Configuration hadoopConf = this.getConf(); // // // TODO: Move this check to a member of each iteration // CompressionType compression = getCompressionType(module, hadoopConf); // if (compression == CompressionType.NONE) { // System.err.println("Using no compression since " // + module.getClass().getSimpleName() // + " module/iteration doesn't support compression..."); // // } else if (compression == CompressionType.GZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.GzipCodec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // // } else if(compression == CompressionType.BZIP) { // hadoopConf.set("mapred.output.compression.codec", // "org.apache.hadoop.io.compress.BZip2Codec"); // hadoopConf.setBoolean("mapred.output.compress", true); // hadoopConf.set("mapred.output.compression.type", "BLOCK"); // System.err // .println("WARNING: Using bzip2 compression since native gzip compression libraries are not available!"); // // } else { // throw new Error("Unrecognized compression type: " + compression); // } // // HadoopConfigApater.dumpToHadoopConfig(opts, hadoopConf); // module.run(hadoopConf); // } // // return 0; // } // // public enum CompressionType { // NONE, GZIP, BZIP // }; // // public static CompressionType getCompressionType(HadoopIteration it, Configuration hadoopConf) { // // boolean gzipCompress = NativeCodeLoader.isNativeCodeLoaded() // && ZlibFactory.isNativeZlibLoaded(hadoopConf); // if (it instanceof DiscountsIteration // || it instanceof VocabIteration) { // return CompressionType.NONE; // } else if(gzipCompress) { // return CompressionType.GZIP; // } else { // return CompressionType.BZIP; // } // } // // public static void main(String[] args) throws Exception { // int res = ToolRunner.run(new Configuration(), new BigFatLM(), args); // System.exit(res); // } // } // Path: src/bigfat/datastructs/FastIntArrayList.java import java.util.concurrent.atomic.AtomicInteger; import bigfat.BigFatLM; sub.globalRevision = this.globalRevision; sub.mutable = false; } // TODO: Check bounds? sub.data = this.data; sub.start = this.start + i; sub.end = this.start + j; return sub; } public void clear() { start = 0; end = 0; if (PARANOID) { myRevision = globalRevision.incrementAndGet(); } } // ZEROTON_ID is assumed to come first // TODO: Move this compareTo() to more specific location public int compareTo(FastIntArrayList other) { for (int i = 0; i < this.size() || i < other.size(); i++) { if (i >= this.size()) { return -1; } else if (i >= other.size()) { return 1; } else { int myId = this.get(i); int otherId = other.get(i); if (myId != otherId) {
if(myId == BigFatLM.ZEROTON_ID) {