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 |
|---|---|---|---|---|---|---|
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/utils/ViewUtils.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
// if (reference == null) {
// throw new NullPointerException(get(errorMessage));
// }
// return reference;
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.checkNotNull;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get; | package com.lucilu.rxdynamicsearch.utils;
public final class ViewUtils {
@SuppressWarnings("unchecked")
@NonNull
public static <T extends View> T find(@NonNull final Activity activity, int id) { | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
// if (reference == null) {
// throw new NullPointerException(get(errorMessage));
// }
// return reference;
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/ViewUtils.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.checkNotNull;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get;
package com.lucilu.rxdynamicsearch.utils;
public final class ViewUtils {
@SuppressWarnings("unchecked")
@NonNull
public static <T extends View> T find(@NonNull final Activity activity, int id) { | checkNotNull(activity, "The activity cannot be null"); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/utils/ViewUtils.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
// if (reference == null) {
// throw new NullPointerException(get(errorMessage));
// }
// return reference;
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.checkNotNull;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get; | package com.lucilu.rxdynamicsearch.utils;
public final class ViewUtils {
@SuppressWarnings("unchecked")
@NonNull
public static <T extends View> T find(@NonNull final Activity activity, int id) {
checkNotNull(activity, "The activity cannot be null");
| // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// public static <T> T checkNotNull(final T reference, @NonNull final String errorMessage) {
// if (reference == null) {
// throw new NullPointerException(get(errorMessage));
// }
// return reference;
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/ViewUtils.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.View;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.checkNotNull;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get;
package com.lucilu.rxdynamicsearch.utils;
public final class ViewUtils {
@SuppressWarnings("unchecked")
@NonNull
public static <T extends View> T find(@NonNull final Activity activity, int id) {
checkNotNull(activity, "The activity cannot be null");
| return (T) get(activity.findViewById(id)); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/AppComponent.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/SearchApplication.java
// public final class SearchApplication extends Application {
//
// @Inject
// Timber.Tree mTimberTree;
//
// @Nullable
// private AppComponent mComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// onInject();
// initializeLogging();
// }
//
// private void onInject() {
// mComponent = AppComponent.Initializer.init(this);
// mComponent.inject(this);
// }
//
// private void initializeLogging() {
// Timber.plant(mTimberTree);
// }
//
// @NonNull
// public AppComponent getAppComponent() {
// return get(mComponent);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/AppModule.java
// @Module
// public final class AppModule {
//
// @NonNull
// private final Application mApplication;
//
// public AppModule(@NonNull final Application app) {
// mApplication = get(app);
// }
//
// @Singleton
// @Provides
// Application providesApplication() {
// return mApplication;
// }
//
// @Singleton
// @ForApplication
// @Provides
// Context providesApplicationContext() {
// return mApplication.getApplicationContext();
// }
// }
//
// Path: app/src/debug/java/com/lucilu/rxdynamicsearch/dagger/module/InstrumentationModule.java
// @Module
// public class InstrumentationModule {
//
// @Singleton
// @Provides
// Timber.Tree provideTimberTree() {
// return new Timber.DebugTree();
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ProviderModule.java
// @Module(includes = DataModule.class)
// public final class ProviderModule {
//
// @Provides
// IResourceProvider provideResourceProvider(@ForApplication final Context context) {
// return new ResourceProvider(context);
// }
//
// @Provides
// IJsonParserProvider provideJsonParserProvider(@NonNull final Gson gson,
// @NonNull final IResourceProvider resourceProvider) {
// return new JsonParserProvider(gson, resourceProvider);
// }
// }
| import com.lucilu.rxdynamicsearch.SearchApplication;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.AppModule;
import com.lucilu.rxdynamicsearch.dagger.module.InstrumentationModule;
import com.lucilu.rxdynamicsearch.dagger.module.ProviderModule;
import javax.inject.Singleton;
import dagger.Component; | package com.lucilu.rxdynamicsearch.dagger.component;
/**
* Top level injection component.
*/
@Singleton
@Component(modules = {InstrumentationModule.class, AppModule.class, ProviderModule.class})
public interface AppComponent {
| // Path: app/src/main/java/com/lucilu/rxdynamicsearch/SearchApplication.java
// public final class SearchApplication extends Application {
//
// @Inject
// Timber.Tree mTimberTree;
//
// @Nullable
// private AppComponent mComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// onInject();
// initializeLogging();
// }
//
// private void onInject() {
// mComponent = AppComponent.Initializer.init(this);
// mComponent.inject(this);
// }
//
// private void initializeLogging() {
// Timber.plant(mTimberTree);
// }
//
// @NonNull
// public AppComponent getAppComponent() {
// return get(mComponent);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/AppModule.java
// @Module
// public final class AppModule {
//
// @NonNull
// private final Application mApplication;
//
// public AppModule(@NonNull final Application app) {
// mApplication = get(app);
// }
//
// @Singleton
// @Provides
// Application providesApplication() {
// return mApplication;
// }
//
// @Singleton
// @ForApplication
// @Provides
// Context providesApplicationContext() {
// return mApplication.getApplicationContext();
// }
// }
//
// Path: app/src/debug/java/com/lucilu/rxdynamicsearch/dagger/module/InstrumentationModule.java
// @Module
// public class InstrumentationModule {
//
// @Singleton
// @Provides
// Timber.Tree provideTimberTree() {
// return new Timber.DebugTree();
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ProviderModule.java
// @Module(includes = DataModule.class)
// public final class ProviderModule {
//
// @Provides
// IResourceProvider provideResourceProvider(@ForApplication final Context context) {
// return new ResourceProvider(context);
// }
//
// @Provides
// IJsonParserProvider provideJsonParserProvider(@NonNull final Gson gson,
// @NonNull final IResourceProvider resourceProvider) {
// return new JsonParserProvider(gson, resourceProvider);
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/AppComponent.java
import com.lucilu.rxdynamicsearch.SearchApplication;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.AppModule;
import com.lucilu.rxdynamicsearch.dagger.module.InstrumentationModule;
import com.lucilu.rxdynamicsearch.dagger.module.ProviderModule;
import javax.inject.Singleton;
import dagger.Component;
package com.lucilu.rxdynamicsearch.dagger.component;
/**
* Top level injection component.
*/
@Singleton
@Component(modules = {InstrumentationModule.class, AppModule.class, ProviderModule.class})
public interface AppComponent {
| void inject(SearchApplication app); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/AppComponent.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/SearchApplication.java
// public final class SearchApplication extends Application {
//
// @Inject
// Timber.Tree mTimberTree;
//
// @Nullable
// private AppComponent mComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// onInject();
// initializeLogging();
// }
//
// private void onInject() {
// mComponent = AppComponent.Initializer.init(this);
// mComponent.inject(this);
// }
//
// private void initializeLogging() {
// Timber.plant(mTimberTree);
// }
//
// @NonNull
// public AppComponent getAppComponent() {
// return get(mComponent);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/AppModule.java
// @Module
// public final class AppModule {
//
// @NonNull
// private final Application mApplication;
//
// public AppModule(@NonNull final Application app) {
// mApplication = get(app);
// }
//
// @Singleton
// @Provides
// Application providesApplication() {
// return mApplication;
// }
//
// @Singleton
// @ForApplication
// @Provides
// Context providesApplicationContext() {
// return mApplication.getApplicationContext();
// }
// }
//
// Path: app/src/debug/java/com/lucilu/rxdynamicsearch/dagger/module/InstrumentationModule.java
// @Module
// public class InstrumentationModule {
//
// @Singleton
// @Provides
// Timber.Tree provideTimberTree() {
// return new Timber.DebugTree();
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ProviderModule.java
// @Module(includes = DataModule.class)
// public final class ProviderModule {
//
// @Provides
// IResourceProvider provideResourceProvider(@ForApplication final Context context) {
// return new ResourceProvider(context);
// }
//
// @Provides
// IJsonParserProvider provideJsonParserProvider(@NonNull final Gson gson,
// @NonNull final IResourceProvider resourceProvider) {
// return new JsonParserProvider(gson, resourceProvider);
// }
// }
| import com.lucilu.rxdynamicsearch.SearchApplication;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.AppModule;
import com.lucilu.rxdynamicsearch.dagger.module.InstrumentationModule;
import com.lucilu.rxdynamicsearch.dagger.module.ProviderModule;
import javax.inject.Singleton;
import dagger.Component; | package com.lucilu.rxdynamicsearch.dagger.component;
/**
* Top level injection component.
*/
@Singleton
@Component(modules = {InstrumentationModule.class, AppModule.class, ProviderModule.class})
public interface AppComponent {
void inject(SearchApplication app);
| // Path: app/src/main/java/com/lucilu/rxdynamicsearch/SearchApplication.java
// public final class SearchApplication extends Application {
//
// @Inject
// Timber.Tree mTimberTree;
//
// @Nullable
// private AppComponent mComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// onInject();
// initializeLogging();
// }
//
// private void onInject() {
// mComponent = AppComponent.Initializer.init(this);
// mComponent.inject(this);
// }
//
// private void initializeLogging() {
// Timber.plant(mTimberTree);
// }
//
// @NonNull
// public AppComponent getAppComponent() {
// return get(mComponent);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/AppModule.java
// @Module
// public final class AppModule {
//
// @NonNull
// private final Application mApplication;
//
// public AppModule(@NonNull final Application app) {
// mApplication = get(app);
// }
//
// @Singleton
// @Provides
// Application providesApplication() {
// return mApplication;
// }
//
// @Singleton
// @ForApplication
// @Provides
// Context providesApplicationContext() {
// return mApplication.getApplicationContext();
// }
// }
//
// Path: app/src/debug/java/com/lucilu/rxdynamicsearch/dagger/module/InstrumentationModule.java
// @Module
// public class InstrumentationModule {
//
// @Singleton
// @Provides
// Timber.Tree provideTimberTree() {
// return new Timber.DebugTree();
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ProviderModule.java
// @Module(includes = DataModule.class)
// public final class ProviderModule {
//
// @Provides
// IResourceProvider provideResourceProvider(@ForApplication final Context context) {
// return new ResourceProvider(context);
// }
//
// @Provides
// IJsonParserProvider provideJsonParserProvider(@NonNull final Gson gson,
// @NonNull final IResourceProvider resourceProvider) {
// return new JsonParserProvider(gson, resourceProvider);
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/AppComponent.java
import com.lucilu.rxdynamicsearch.SearchApplication;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.AppModule;
import com.lucilu.rxdynamicsearch.dagger.module.InstrumentationModule;
import com.lucilu.rxdynamicsearch.dagger.module.ProviderModule;
import javax.inject.Singleton;
import dagger.Component;
package com.lucilu.rxdynamicsearch.dagger.component;
/**
* Top level injection component.
*/
@Singleton
@Component(modules = {InstrumentationModule.class, AppModule.class, ProviderModule.class})
public interface AppComponent {
void inject(SearchApplication app);
| MainActivityComponent plusMainActivity(ActivityModule activityModule); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/service/SearchService.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
| import android.support.annotation.NonNull;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import static com.lucilu.rxdynamicsearch.Constants.DYNAMIC_SEARCH_DELAY_MILLIS;
import static com.lucilu.rxdynamicsearch.Constants.EMPTY_QUERY;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get; | package com.lucilu.rxdynamicsearch.service;
public class SearchService {
private final PublishSubject<String> dynamicQueryStream = PublishSubject.create();
private final PublishSubject<String> submittedQueryStream = PublishSubject.create();
private final Observable<String> searchQueryStream;
public SearchService() {
searchQueryStream = defineSearchQueryStream();
}
private Observable<String> defineSearchQueryStream() {
return Observable
.merge(defineDynamicQueryStream(), defineSubmittedQueryStream())
.map(String::trim)
.startWith(EMPTY_QUERY)
.distinctUntilChanged();
}
private Observable<String> defineDynamicQueryStream() {
return dynamicQueryStream
.debounce(DYNAMIC_SEARCH_DELAY_MILLIS,
TimeUnit.MILLISECONDS,
Schedulers.computation());
}
private Observable<String> defineSubmittedQueryStream() {
return submittedQueryStream;
}
public void queryTextChanged(@NonNull final String query) { | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/service/SearchService.java
import android.support.annotation.NonNull;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import static com.lucilu.rxdynamicsearch.Constants.DYNAMIC_SEARCH_DELAY_MILLIS;
import static com.lucilu.rxdynamicsearch.Constants.EMPTY_QUERY;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get;
package com.lucilu.rxdynamicsearch.service;
public class SearchService {
private final PublishSubject<String> dynamicQueryStream = PublishSubject.create();
private final PublishSubject<String> submittedQueryStream = PublishSubject.create();
private final Observable<String> searchQueryStream;
public SearchService() {
searchQueryStream = defineSearchQueryStream();
}
private Observable<String> defineSearchQueryStream() {
return Observable
.merge(defineDynamicQueryStream(), defineSubmittedQueryStream())
.map(String::trim)
.startWith(EMPTY_QUERY)
.distinctUntilChanged();
}
private Observable<String> defineDynamicQueryStream() {
return dynamicQueryStream
.debounce(DYNAMIC_SEARCH_DELAY_MILLIS,
TimeUnit.MILLISECONDS,
Schedulers.computation());
}
private Observable<String> defineSubmittedQueryStream() {
return submittedQueryStream;
}
public void queryTextChanged(@NonNull final String query) { | dynamicQueryStream.onNext(get(query)); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/repository/base/ICountryRepository.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
| import com.lucilu.rxdynamicsearch.data.pojo.Country;
import android.support.annotation.NonNull;
import java.util.List;
import polanski.option.Option;
import rx.Observable; | package com.lucilu.rxdynamicsearch.repository.base;
/**
* Countries repository.
*/
public interface ICountryRepository {
/**
* Gets all the countries.
*
* @return list with all the countries.
*/
@NonNull | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/repository/base/ICountryRepository.java
import com.lucilu.rxdynamicsearch.data.pojo.Country;
import android.support.annotation.NonNull;
import java.util.List;
import polanski.option.Option;
import rx.Observable;
package com.lucilu.rxdynamicsearch.repository.base;
/**
* Countries repository.
*/
public interface ICountryRepository {
/**
* Gets all the countries.
*
* @return list with all the countries.
*/
@NonNull | Observable<Option<List<Country>>> getAllCountries(); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/provider/ResourceProvider.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/provider/base/IResourceProvider.java
// public interface IResourceProvider {
//
// /**
// * {@link Resources#openRawResource(int)}
// */
// @NonNull
// InputStream openRawResource(final int id);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
| import com.lucilu.rxdynamicsearch.provider.base.IResourceProvider;
import android.content.Context;
import android.support.annotation.NonNull;
import java.io.InputStream;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get; | package com.lucilu.rxdynamicsearch.provider;
public final class ResourceProvider implements IResourceProvider {
@NonNull
private final Context mContext;
public ResourceProvider(@NonNull final Context context) { | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/provider/base/IResourceProvider.java
// public interface IResourceProvider {
//
// /**
// * {@link Resources#openRawResource(int)}
// */
// @NonNull
// InputStream openRawResource(final int id);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/utils/Preconditions.java
// @NonNull
// public static <T> T get(@Nullable final T reference) {
// if (reference == null) {
// throw new NullPointerException("Assertion for a nonnull object failed.");
// }
// return reference;
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/provider/ResourceProvider.java
import com.lucilu.rxdynamicsearch.provider.base.IResourceProvider;
import android.content.Context;
import android.support.annotation.NonNull;
import java.io.InputStream;
import static com.lucilu.rxdynamicsearch.utils.Preconditions.get;
package com.lucilu.rxdynamicsearch.provider;
public final class ResourceProvider implements IResourceProvider {
@NonNull
private final Context mContext;
public ResourceProvider(@NonNull final Context context) { | mContext = get(context); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/MainActivityComponent.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/activities/MainActivity.java
// public final class MainActivity extends BaseActivity {
//
// @Nullable
// private MainActivityComponent mComponent;
//
// @Override
// protected void onCreate(@Nullable final Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override
// protected void onBind(@NonNull final CompositeSubscription subscription) {
// // DO nothing (for now)
// }
//
// @Override
// public void onInject() {
// mComponent = createComponent();
// mComponent.inject(this);
// }
//
// @NonNull
// public MainActivityComponent getComponent() {
// return get(mComponent);
// }
//
// private MainActivityComponent createComponent() {
// SearchApplication app = (SearchApplication) getApplication();
// ActivityModule activityModule = new ActivityModule(this);
//
// return app.getAppComponent().plusMainActivity(activityModule);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/RepositoryModule.java
// @Module
// public final class RepositoryModule {
//
// @Provides
// ICountryRepository provideCountryRepository(final IJsonParserProvider jsonParserProvider) {
// return new CountryRepository(jsonParserProvider);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/SearchFragmentModule.java
// @Module
// public final class SearchFragmentModule {
//
// @NonNull
// private final Observable<CharSequence> mQueryStream;
//
// public SearchFragmentModule(@NonNull final Observable<CharSequence> queryStream) {
// mQueryStream = get(queryStream);
// }
//
// @FragmentScope
// @Provides
// Observable<CharSequence> providesQueryStream() {
// return mQueryStream;
// }
// }
| import com.lucilu.rxdynamicsearch.activities.MainActivity;
import com.lucilu.rxdynamicsearch.dagger.Scopes.ActivityScope;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.RepositoryModule;
import com.lucilu.rxdynamicsearch.dagger.module.SearchFragmentModule;
import dagger.Subcomponent; | package com.lucilu.rxdynamicsearch.dagger.component;
/**
* {@link MainActivity} component.
*/
@ActivityScope
@Subcomponent(modules = {ActivityModule.class, RepositoryModule.class})
public interface MainActivityComponent {
| // Path: app/src/main/java/com/lucilu/rxdynamicsearch/activities/MainActivity.java
// public final class MainActivity extends BaseActivity {
//
// @Nullable
// private MainActivityComponent mComponent;
//
// @Override
// protected void onCreate(@Nullable final Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override
// protected void onBind(@NonNull final CompositeSubscription subscription) {
// // DO nothing (for now)
// }
//
// @Override
// public void onInject() {
// mComponent = createComponent();
// mComponent.inject(this);
// }
//
// @NonNull
// public MainActivityComponent getComponent() {
// return get(mComponent);
// }
//
// private MainActivityComponent createComponent() {
// SearchApplication app = (SearchApplication) getApplication();
// ActivityModule activityModule = new ActivityModule(this);
//
// return app.getAppComponent().plusMainActivity(activityModule);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/RepositoryModule.java
// @Module
// public final class RepositoryModule {
//
// @Provides
// ICountryRepository provideCountryRepository(final IJsonParserProvider jsonParserProvider) {
// return new CountryRepository(jsonParserProvider);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/SearchFragmentModule.java
// @Module
// public final class SearchFragmentModule {
//
// @NonNull
// private final Observable<CharSequence> mQueryStream;
//
// public SearchFragmentModule(@NonNull final Observable<CharSequence> queryStream) {
// mQueryStream = get(queryStream);
// }
//
// @FragmentScope
// @Provides
// Observable<CharSequence> providesQueryStream() {
// return mQueryStream;
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/MainActivityComponent.java
import com.lucilu.rxdynamicsearch.activities.MainActivity;
import com.lucilu.rxdynamicsearch.dagger.Scopes.ActivityScope;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.RepositoryModule;
import com.lucilu.rxdynamicsearch.dagger.module.SearchFragmentModule;
import dagger.Subcomponent;
package com.lucilu.rxdynamicsearch.dagger.component;
/**
* {@link MainActivity} component.
*/
@ActivityScope
@Subcomponent(modules = {ActivityModule.class, RepositoryModule.class})
public interface MainActivityComponent {
| void inject(MainActivity activity); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/MainActivityComponent.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/activities/MainActivity.java
// public final class MainActivity extends BaseActivity {
//
// @Nullable
// private MainActivityComponent mComponent;
//
// @Override
// protected void onCreate(@Nullable final Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override
// protected void onBind(@NonNull final CompositeSubscription subscription) {
// // DO nothing (for now)
// }
//
// @Override
// public void onInject() {
// mComponent = createComponent();
// mComponent.inject(this);
// }
//
// @NonNull
// public MainActivityComponent getComponent() {
// return get(mComponent);
// }
//
// private MainActivityComponent createComponent() {
// SearchApplication app = (SearchApplication) getApplication();
// ActivityModule activityModule = new ActivityModule(this);
//
// return app.getAppComponent().plusMainActivity(activityModule);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/RepositoryModule.java
// @Module
// public final class RepositoryModule {
//
// @Provides
// ICountryRepository provideCountryRepository(final IJsonParserProvider jsonParserProvider) {
// return new CountryRepository(jsonParserProvider);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/SearchFragmentModule.java
// @Module
// public final class SearchFragmentModule {
//
// @NonNull
// private final Observable<CharSequence> mQueryStream;
//
// public SearchFragmentModule(@NonNull final Observable<CharSequence> queryStream) {
// mQueryStream = get(queryStream);
// }
//
// @FragmentScope
// @Provides
// Observable<CharSequence> providesQueryStream() {
// return mQueryStream;
// }
// }
| import com.lucilu.rxdynamicsearch.activities.MainActivity;
import com.lucilu.rxdynamicsearch.dagger.Scopes.ActivityScope;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.RepositoryModule;
import com.lucilu.rxdynamicsearch.dagger.module.SearchFragmentModule;
import dagger.Subcomponent; | package com.lucilu.rxdynamicsearch.dagger.component;
/**
* {@link MainActivity} component.
*/
@ActivityScope
@Subcomponent(modules = {ActivityModule.class, RepositoryModule.class})
public interface MainActivityComponent {
void inject(MainActivity activity);
| // Path: app/src/main/java/com/lucilu/rxdynamicsearch/activities/MainActivity.java
// public final class MainActivity extends BaseActivity {
//
// @Nullable
// private MainActivityComponent mComponent;
//
// @Override
// protected void onCreate(@Nullable final Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//
// @Override
// protected void onBind(@NonNull final CompositeSubscription subscription) {
// // DO nothing (for now)
// }
//
// @Override
// public void onInject() {
// mComponent = createComponent();
// mComponent.inject(this);
// }
//
// @NonNull
// public MainActivityComponent getComponent() {
// return get(mComponent);
// }
//
// private MainActivityComponent createComponent() {
// SearchApplication app = (SearchApplication) getApplication();
// ActivityModule activityModule = new ActivityModule(this);
//
// return app.getAppComponent().plusMainActivity(activityModule);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/ActivityModule.java
// @Module
// public final class ActivityModule {
//
// @NonNull
// private final Activity mActivity;
//
// public ActivityModule(@NonNull final Activity activity) {
// mActivity = get(activity);
// }
//
// @ActivityScope
// @Provides
// Activity providesActivity() {
// return mActivity;
// }
//
// @ActivityScope
// @ForActivity
// @Provides
// Context providesActivityContext() {
// return mActivity;
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/RepositoryModule.java
// @Module
// public final class RepositoryModule {
//
// @Provides
// ICountryRepository provideCountryRepository(final IJsonParserProvider jsonParserProvider) {
// return new CountryRepository(jsonParserProvider);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/module/SearchFragmentModule.java
// @Module
// public final class SearchFragmentModule {
//
// @NonNull
// private final Observable<CharSequence> mQueryStream;
//
// public SearchFragmentModule(@NonNull final Observable<CharSequence> queryStream) {
// mQueryStream = get(queryStream);
// }
//
// @FragmentScope
// @Provides
// Observable<CharSequence> providesQueryStream() {
// return mQueryStream;
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/dagger/component/MainActivityComponent.java
import com.lucilu.rxdynamicsearch.activities.MainActivity;
import com.lucilu.rxdynamicsearch.dagger.Scopes.ActivityScope;
import com.lucilu.rxdynamicsearch.dagger.module.ActivityModule;
import com.lucilu.rxdynamicsearch.dagger.module.RepositoryModule;
import com.lucilu.rxdynamicsearch.dagger.module.SearchFragmentModule;
import dagger.Subcomponent;
package com.lucilu.rxdynamicsearch.dagger.component;
/**
* {@link MainActivity} component.
*/
@ActivityScope
@Subcomponent(modules = {ActivityModule.class, RepositoryModule.class})
public interface MainActivityComponent {
void inject(MainActivity activity);
| CountryListComponent plusSearchFragment(SearchFragmentModule module); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/rx/Transformers.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/rx/transformer/ChooseTransformer.java
// public final class ChooseTransformer<T>
// implements Observable.Transformer<Option<T>, T> {
//
// @Override
// public Observable<T> call(final Observable<Option<T>> optionObservable) {
// return ObservableEx.choose(optionObservable);
// }
// }
| import com.lucilu.rxdynamicsearch.rx.transformer.ChooseTransformer;
import android.support.annotation.NonNull;
import rx.Observable; | package com.lucilu.rxdynamicsearch.rx;
/**
* Collection of transformers.
*/
public final class Transformers {
private Transformers() {
}
/**
* Returns a {@link Observable.Transformer} that Filters out all Option of NONE if any,
* but if Some, then unwraps and returns the value.
*
* @return choose transformer.
*/
@NonNull | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/rx/transformer/ChooseTransformer.java
// public final class ChooseTransformer<T>
// implements Observable.Transformer<Option<T>, T> {
//
// @Override
// public Observable<T> call(final Observable<Option<T>> optionObservable) {
// return ObservableEx.choose(optionObservable);
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/rx/Transformers.java
import com.lucilu.rxdynamicsearch.rx.transformer.ChooseTransformer;
import android.support.annotation.NonNull;
import rx.Observable;
package com.lucilu.rxdynamicsearch.rx;
/**
* Collection of transformers.
*/
public final class Transformers {
private Transformers() {
}
/**
* Returns a {@link Observable.Transformer} that Filters out all Option of NONE if any,
* but if Some, then unwraps and returns the value.
*
* @return choose transformer.
*/
@NonNull | public static <T> ChooseTransformer<T> choose() { |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/CountryListViewHolderBinder.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Ad.java
// @AutoValue
// public abstract class Ad {
//
// public abstract String header();
//
// public static Ad createAd(@NonNull final String header) {
// return new AutoValue_Ad(header);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/base/IViewHolderBinder.java
// public interface IViewHolderBinder<T> {
//
// /**
// * Populates the passed {@link ViewHolder} with the details of the passed model.
// */
// void bind(@NonNull final ViewHolder viewHolder, @NonNull final T model);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/AdViewHolder.java
// public class AdViewHolder extends SimpleViewHolder<Ad> {
//
// @NonNull
// private final TextView headerTextView;
//
// public AdViewHolder(final View itemView) {
// super(itemView);
//
// headerTextView = ViewUtils.find(itemView, R.id.item_textView_header);
// }
//
// @Override
// public void bind(@NonNull final Ad model) {
// headerTextView.setText(model.header());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/CountryViewHolder.java
// public final class CountryViewHolder extends SimpleViewHolder<Country> {
//
// @NonNull
// private final TextView mCountryName;
//
// @NonNull
// private final TextView mCapital;
//
// public CountryViewHolder(@NonNull final View itemView) {
// super(itemView);
//
// mCountryName = ViewUtils.find(itemView, R.id.item_textView_country);
// mCapital = ViewUtils.find(itemView, R.id.item_textView_capital);
// }
//
// @Override
// public void bind(@NonNull final Country model) {
// populateWith(model);
// }
//
// private void populateWith(@NonNull final Country country) {
// mCountryName.setText(country.getName());
// mCapital.setText(country.getCapital());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/viewmodel/pojo/DisplayableItem.java
// @AutoValue
// public abstract class DisplayableItem<T> {
//
// public abstract int type();
//
// @NonNull
// public abstract T model();
//
// @SuppressWarnings("NullableProblems")
// @AutoValue.Builder
// public abstract static class Builder<T> {
//
// @NonNull
// public abstract Builder<T> type(@NonNull int type);
//
// @NonNull
// public abstract Builder<T> model(@NonNull T model);
//
// @NonNull
// public abstract DisplayableItem<T> build();
// }
//
// @NonNull
// public static <T> Builder<T> builder() {
// return new AutoValue_DisplayableItem.Builder<>();
// }
// }
| import com.lucilu.rxdynamicsearch.data.pojo.Ad;
import com.lucilu.rxdynamicsearch.data.pojo.Country;
import com.lucilu.rxdynamicsearch.ui.adapter.base.IViewHolderBinder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.AdViewHolder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.CountryViewHolder;
import com.lucilu.rxdynamicsearch.viewmodel.pojo.DisplayableItem;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView.ViewHolder;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.AD;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.COUNTRY; | package com.lucilu.rxdynamicsearch.ui.adapter;
public final class CountryListViewHolderBinder implements IViewHolderBinder<DisplayableItem> {
public CountryListViewHolderBinder() {
}
@Override
public void bind(@NonNull final ViewHolder viewHolder,
@NonNull final DisplayableItem displayableItem) {
switch (displayableItem.type()) {
case COUNTRY: | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Ad.java
// @AutoValue
// public abstract class Ad {
//
// public abstract String header();
//
// public static Ad createAd(@NonNull final String header) {
// return new AutoValue_Ad(header);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/base/IViewHolderBinder.java
// public interface IViewHolderBinder<T> {
//
// /**
// * Populates the passed {@link ViewHolder} with the details of the passed model.
// */
// void bind(@NonNull final ViewHolder viewHolder, @NonNull final T model);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/AdViewHolder.java
// public class AdViewHolder extends SimpleViewHolder<Ad> {
//
// @NonNull
// private final TextView headerTextView;
//
// public AdViewHolder(final View itemView) {
// super(itemView);
//
// headerTextView = ViewUtils.find(itemView, R.id.item_textView_header);
// }
//
// @Override
// public void bind(@NonNull final Ad model) {
// headerTextView.setText(model.header());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/CountryViewHolder.java
// public final class CountryViewHolder extends SimpleViewHolder<Country> {
//
// @NonNull
// private final TextView mCountryName;
//
// @NonNull
// private final TextView mCapital;
//
// public CountryViewHolder(@NonNull final View itemView) {
// super(itemView);
//
// mCountryName = ViewUtils.find(itemView, R.id.item_textView_country);
// mCapital = ViewUtils.find(itemView, R.id.item_textView_capital);
// }
//
// @Override
// public void bind(@NonNull final Country model) {
// populateWith(model);
// }
//
// private void populateWith(@NonNull final Country country) {
// mCountryName.setText(country.getName());
// mCapital.setText(country.getCapital());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/viewmodel/pojo/DisplayableItem.java
// @AutoValue
// public abstract class DisplayableItem<T> {
//
// public abstract int type();
//
// @NonNull
// public abstract T model();
//
// @SuppressWarnings("NullableProblems")
// @AutoValue.Builder
// public abstract static class Builder<T> {
//
// @NonNull
// public abstract Builder<T> type(@NonNull int type);
//
// @NonNull
// public abstract Builder<T> model(@NonNull T model);
//
// @NonNull
// public abstract DisplayableItem<T> build();
// }
//
// @NonNull
// public static <T> Builder<T> builder() {
// return new AutoValue_DisplayableItem.Builder<>();
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/CountryListViewHolderBinder.java
import com.lucilu.rxdynamicsearch.data.pojo.Ad;
import com.lucilu.rxdynamicsearch.data.pojo.Country;
import com.lucilu.rxdynamicsearch.ui.adapter.base.IViewHolderBinder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.AdViewHolder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.CountryViewHolder;
import com.lucilu.rxdynamicsearch.viewmodel.pojo.DisplayableItem;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView.ViewHolder;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.AD;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.COUNTRY;
package com.lucilu.rxdynamicsearch.ui.adapter;
public final class CountryListViewHolderBinder implements IViewHolderBinder<DisplayableItem> {
public CountryListViewHolderBinder() {
}
@Override
public void bind(@NonNull final ViewHolder viewHolder,
@NonNull final DisplayableItem displayableItem) {
switch (displayableItem.type()) {
case COUNTRY: | CountryViewHolder countryViewHolder = CountryViewHolder.class.cast(viewHolder); |
luciapayo/RxDynamicSearch | app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/CountryListViewHolderBinder.java | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Ad.java
// @AutoValue
// public abstract class Ad {
//
// public abstract String header();
//
// public static Ad createAd(@NonNull final String header) {
// return new AutoValue_Ad(header);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/base/IViewHolderBinder.java
// public interface IViewHolderBinder<T> {
//
// /**
// * Populates the passed {@link ViewHolder} with the details of the passed model.
// */
// void bind(@NonNull final ViewHolder viewHolder, @NonNull final T model);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/AdViewHolder.java
// public class AdViewHolder extends SimpleViewHolder<Ad> {
//
// @NonNull
// private final TextView headerTextView;
//
// public AdViewHolder(final View itemView) {
// super(itemView);
//
// headerTextView = ViewUtils.find(itemView, R.id.item_textView_header);
// }
//
// @Override
// public void bind(@NonNull final Ad model) {
// headerTextView.setText(model.header());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/CountryViewHolder.java
// public final class CountryViewHolder extends SimpleViewHolder<Country> {
//
// @NonNull
// private final TextView mCountryName;
//
// @NonNull
// private final TextView mCapital;
//
// public CountryViewHolder(@NonNull final View itemView) {
// super(itemView);
//
// mCountryName = ViewUtils.find(itemView, R.id.item_textView_country);
// mCapital = ViewUtils.find(itemView, R.id.item_textView_capital);
// }
//
// @Override
// public void bind(@NonNull final Country model) {
// populateWith(model);
// }
//
// private void populateWith(@NonNull final Country country) {
// mCountryName.setText(country.getName());
// mCapital.setText(country.getCapital());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/viewmodel/pojo/DisplayableItem.java
// @AutoValue
// public abstract class DisplayableItem<T> {
//
// public abstract int type();
//
// @NonNull
// public abstract T model();
//
// @SuppressWarnings("NullableProblems")
// @AutoValue.Builder
// public abstract static class Builder<T> {
//
// @NonNull
// public abstract Builder<T> type(@NonNull int type);
//
// @NonNull
// public abstract Builder<T> model(@NonNull T model);
//
// @NonNull
// public abstract DisplayableItem<T> build();
// }
//
// @NonNull
// public static <T> Builder<T> builder() {
// return new AutoValue_DisplayableItem.Builder<>();
// }
// }
| import com.lucilu.rxdynamicsearch.data.pojo.Ad;
import com.lucilu.rxdynamicsearch.data.pojo.Country;
import com.lucilu.rxdynamicsearch.ui.adapter.base.IViewHolderBinder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.AdViewHolder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.CountryViewHolder;
import com.lucilu.rxdynamicsearch.viewmodel.pojo.DisplayableItem;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView.ViewHolder;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.AD;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.COUNTRY; | package com.lucilu.rxdynamicsearch.ui.adapter;
public final class CountryListViewHolderBinder implements IViewHolderBinder<DisplayableItem> {
public CountryListViewHolderBinder() {
}
@Override
public void bind(@NonNull final ViewHolder viewHolder,
@NonNull final DisplayableItem displayableItem) {
switch (displayableItem.type()) {
case COUNTRY:
CountryViewHolder countryViewHolder = CountryViewHolder.class.cast(viewHolder); | // Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Ad.java
// @AutoValue
// public abstract class Ad {
//
// public abstract String header();
//
// public static Ad createAd(@NonNull final String header) {
// return new AutoValue_Ad(header);
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/data/pojo/Country.java
// public final class Country {
//
// @NonNull
// @SerializedName("name")
// private final String mName;
//
// @NonNull
// @SerializedName("capital")
// private final String mCapital;
//
// @NonNull
// @SerializedName("region")
// private final String mRegion;
//
// public Country(@NonNull final String name,
// @NonNull final String capital,
// @NonNull final String region) {
// mName = get(name);
// mCapital = get(capital);
// mRegion = get(region);
// }
//
// @NonNull
// public String getName() {
// return mName;
// }
//
// @NonNull
// public String getCapital() {
// return mCapital;
// }
//
// @NonNull
// public String getRegion() {
// return mRegion;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// final Country country = (Country) o;
//
// if (!mName.equals(country.mName)) {
// return false;
// }
// if (!mCapital.equals(country.mCapital)) {
// return false;
// }
// return mRegion.equals(country.mRegion);
//
// }
//
// @Override
// public int hashCode() {
// int result = mName.hashCode();
// result = 31 * result + mCapital.hashCode();
// result = 31 * result + mRegion.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Country{" +
// "mName='" + mName + '\'' +
// ", mCapital='" + mCapital + '\'' +
// ", mRegion='" + mRegion + '\'' +
// '}';
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/base/IViewHolderBinder.java
// public interface IViewHolderBinder<T> {
//
// /**
// * Populates the passed {@link ViewHolder} with the details of the passed model.
// */
// void bind(@NonNull final ViewHolder viewHolder, @NonNull final T model);
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/AdViewHolder.java
// public class AdViewHolder extends SimpleViewHolder<Ad> {
//
// @NonNull
// private final TextView headerTextView;
//
// public AdViewHolder(final View itemView) {
// super(itemView);
//
// headerTextView = ViewUtils.find(itemView, R.id.item_textView_header);
// }
//
// @Override
// public void bind(@NonNull final Ad model) {
// headerTextView.setText(model.header());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/viewholder/CountryViewHolder.java
// public final class CountryViewHolder extends SimpleViewHolder<Country> {
//
// @NonNull
// private final TextView mCountryName;
//
// @NonNull
// private final TextView mCapital;
//
// public CountryViewHolder(@NonNull final View itemView) {
// super(itemView);
//
// mCountryName = ViewUtils.find(itemView, R.id.item_textView_country);
// mCapital = ViewUtils.find(itemView, R.id.item_textView_capital);
// }
//
// @Override
// public void bind(@NonNull final Country model) {
// populateWith(model);
// }
//
// private void populateWith(@NonNull final Country country) {
// mCountryName.setText(country.getName());
// mCapital.setText(country.getCapital());
// }
// }
//
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/viewmodel/pojo/DisplayableItem.java
// @AutoValue
// public abstract class DisplayableItem<T> {
//
// public abstract int type();
//
// @NonNull
// public abstract T model();
//
// @SuppressWarnings("NullableProblems")
// @AutoValue.Builder
// public abstract static class Builder<T> {
//
// @NonNull
// public abstract Builder<T> type(@NonNull int type);
//
// @NonNull
// public abstract Builder<T> model(@NonNull T model);
//
// @NonNull
// public abstract DisplayableItem<T> build();
// }
//
// @NonNull
// public static <T> Builder<T> builder() {
// return new AutoValue_DisplayableItem.Builder<>();
// }
// }
// Path: app/src/main/java/com/lucilu/rxdynamicsearch/ui/adapter/CountryListViewHolderBinder.java
import com.lucilu.rxdynamicsearch.data.pojo.Ad;
import com.lucilu.rxdynamicsearch.data.pojo.Country;
import com.lucilu.rxdynamicsearch.ui.adapter.base.IViewHolderBinder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.AdViewHolder;
import com.lucilu.rxdynamicsearch.ui.adapter.viewholder.CountryViewHolder;
import com.lucilu.rxdynamicsearch.viewmodel.pojo.DisplayableItem;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView.ViewHolder;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.AD;
import static com.lucilu.rxdynamicsearch.Constants.ListItem.COUNTRY;
package com.lucilu.rxdynamicsearch.ui.adapter;
public final class CountryListViewHolderBinder implements IViewHolderBinder<DisplayableItem> {
public CountryListViewHolderBinder() {
}
@Override
public void bind(@NonNull final ViewHolder viewHolder,
@NonNull final DisplayableItem displayableItem) {
switch (displayableItem.type()) {
case COUNTRY:
CountryViewHolder countryViewHolder = CountryViewHolder.class.cast(viewHolder); | Country country = Country.class.cast(displayableItem.model()); |
centralperf/centralperf | src/main/java/org/centralperf/controller/BootstrapController.java | // Path: src/main/java/org/centralperf/service/BootstrapService.java
// @Service
// public class BootstrapService implements InitializingBean {
//
// @Resource
// private ConfigurationService configurationService;
//
// @Resource
// private ScriptService scriptService;
//
// @Resource
// private ProjectService projectService;
//
// @Resource
// private BootstrapServiceFiles bootstrapServiceFiles;
//
// @Resource
// private RunRepository runRepository;
//
// private static final Logger log = LoggerFactory.getLogger(BootstrapService.class);
//
// /**
// * Check if it's necessary to launch bootstrap.
// * If the user has already imported sample data or refused it, then it returns false
// *
// * @return true if already initialized, false otherwise
// */
// public boolean isAlreadyInitialized() {
// Boolean initialized = Boolean.parseBoolean(configurationService.getConfigurationValue(Configuration.INITIALIZED));
// return initialized != null ? initialized : false;
// }
//
// public void setInitialized() {
// // Update configuration, set as initialized
// configurationService.updateConfigurationValue(Configuration.INITIALIZED, Boolean.TRUE.toString());
// }
//
// public void importSamples() {
//
// // Create sample Projet
// Project sampleProject = new Project();
// sampleProject.setName("Sample project");
// sampleProject.setDescription("Central Perf default sample Project");
// projectService.addProject(sampleProject);
//
// // Associate sample script
// // Load sample JMX and Gatling files
// String jmxContent;
// //String gatlingContent;
// jmxContent = new Scanner(bootstrapServiceFiles.getSampleJMXFile()).useDelimiter("\\Z").next();
// scriptService.addScript(sampleProject, JMeterSampler.UID, "JMETER Sample script", "Central Perf sample JMETER script. Queries a single URL with few scenario's parameters", jmxContent);
// //gatlingContent = new Scanner(bootstrapServiceFiles.getSampleGatlingFile().getFile()).useDelimiter("\\Z").next();
// //scriptService.addScript(sampleProject,GatlingSampler.UID, "GATLING Sample script", "Central Perf sample script. Queries Google; only for demonstration (no parameters)", gatlingContent);
// // Import sample resuts
// // TODO : Import sample result
// }
//
// /**
// * Check if jobs where running while the application stopped (after a crash for example ...)
// * These runs should not be running on startup
// */
// private void fixIncompleteRuns() {
// List<Run> incompleteRuns = runRepository.findByRunning(true);
// for (Run incompleteRun : incompleteRuns) {
// incompleteRun.setRunning(false);
// incompleteRun.setComment(
// (incompleteRun.getComment() != null ? incompleteRun.getComment() : "") +
// "\r\n*** System message : this run didn't complete normally *** ");
// runRepository.save(incompleteRun);
// }
// }
//
// /**
// * Launched after container started
// *
// * @throws Exception
// */
// @Override
// public void afterPropertiesSet() throws Exception {
// log.debug("Launch bootstrap actions");
//
// log.debug("fix uncomplete runs");
// fixIncompleteRuns();
// }
//
// }
| import javax.annotation.Resource;
import org.centralperf.service.BootstrapService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.controller;
/**
* The Bootstrap controller is used when CP is launched for the first time, to propose to initialize with samples
*
* @since 1.0
*
*/
@Controller
public class BootstrapController {
@Resource | // Path: src/main/java/org/centralperf/service/BootstrapService.java
// @Service
// public class BootstrapService implements InitializingBean {
//
// @Resource
// private ConfigurationService configurationService;
//
// @Resource
// private ScriptService scriptService;
//
// @Resource
// private ProjectService projectService;
//
// @Resource
// private BootstrapServiceFiles bootstrapServiceFiles;
//
// @Resource
// private RunRepository runRepository;
//
// private static final Logger log = LoggerFactory.getLogger(BootstrapService.class);
//
// /**
// * Check if it's necessary to launch bootstrap.
// * If the user has already imported sample data or refused it, then it returns false
// *
// * @return true if already initialized, false otherwise
// */
// public boolean isAlreadyInitialized() {
// Boolean initialized = Boolean.parseBoolean(configurationService.getConfigurationValue(Configuration.INITIALIZED));
// return initialized != null ? initialized : false;
// }
//
// public void setInitialized() {
// // Update configuration, set as initialized
// configurationService.updateConfigurationValue(Configuration.INITIALIZED, Boolean.TRUE.toString());
// }
//
// public void importSamples() {
//
// // Create sample Projet
// Project sampleProject = new Project();
// sampleProject.setName("Sample project");
// sampleProject.setDescription("Central Perf default sample Project");
// projectService.addProject(sampleProject);
//
// // Associate sample script
// // Load sample JMX and Gatling files
// String jmxContent;
// //String gatlingContent;
// jmxContent = new Scanner(bootstrapServiceFiles.getSampleJMXFile()).useDelimiter("\\Z").next();
// scriptService.addScript(sampleProject, JMeterSampler.UID, "JMETER Sample script", "Central Perf sample JMETER script. Queries a single URL with few scenario's parameters", jmxContent);
// //gatlingContent = new Scanner(bootstrapServiceFiles.getSampleGatlingFile().getFile()).useDelimiter("\\Z").next();
// //scriptService.addScript(sampleProject,GatlingSampler.UID, "GATLING Sample script", "Central Perf sample script. Queries Google; only for demonstration (no parameters)", gatlingContent);
// // Import sample resuts
// // TODO : Import sample result
// }
//
// /**
// * Check if jobs where running while the application stopped (after a crash for example ...)
// * These runs should not be running on startup
// */
// private void fixIncompleteRuns() {
// List<Run> incompleteRuns = runRepository.findByRunning(true);
// for (Run incompleteRun : incompleteRuns) {
// incompleteRun.setRunning(false);
// incompleteRun.setComment(
// (incompleteRun.getComment() != null ? incompleteRun.getComment() : "") +
// "\r\n*** System message : this run didn't complete normally *** ");
// runRepository.save(incompleteRun);
// }
// }
//
// /**
// * Launched after container started
// *
// * @throws Exception
// */
// @Override
// public void afterPropertiesSet() throws Exception {
// log.debug("Launch bootstrap actions");
//
// log.debug("fix uncomplete runs");
// fixIncompleteRuns();
// }
//
// }
// Path: src/main/java/org/centralperf/controller/BootstrapController.java
import javax.annotation.Resource;
import org.centralperf.service.BootstrapService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.controller;
/**
* The Bootstrap controller is used when CP is launched for the first time, to propose to initialize with samples
*
* @since 1.0
*
*/
@Controller
public class BootstrapController {
@Resource | BootstrapService bootstrapService; |
centralperf/centralperf | src/main/java/org/centralperf/service/SamplerService.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
// @Deprecated
// public class GatlingSampler implements Sampler {
//
// @Resource
// private GatlingLauncher launcher;
//
// @Resource
// private GatlingScriptProcessor scriptProcessor;
//
// public static final String UID = "GATLING_1_X";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "Gatling 1.x";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".scala";
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
// @Component
// public class JMeterSampler implements Sampler {
//
// @Resource
// private JMeterLauncher launcher;
//
// @Resource
// private JMeterScriptProcessor scriptProcessor;
//
// public static final String UID = "JMETER_LOCAL";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "JMeter local";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".jmx";
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.driver.gatling.GatlingSampler;
import org.centralperf.sampler.driver.jmeter.JMeterSampler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.service;
/**
* Manager available sampler types (JMeter, Gatling...)
* @since 1.0
*
*/
@Service
public class SamplerService implements InitializingBean{
| // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
// @Deprecated
// public class GatlingSampler implements Sampler {
//
// @Resource
// private GatlingLauncher launcher;
//
// @Resource
// private GatlingScriptProcessor scriptProcessor;
//
// public static final String UID = "GATLING_1_X";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "Gatling 1.x";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".scala";
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
// @Component
// public class JMeterSampler implements Sampler {
//
// @Resource
// private JMeterLauncher launcher;
//
// @Resource
// private JMeterScriptProcessor scriptProcessor;
//
// public static final String UID = "JMETER_LOCAL";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "JMeter local";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".jmx";
// }
//
// }
// Path: src/main/java/org/centralperf/service/SamplerService.java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.driver.gatling.GatlingSampler;
import org.centralperf.sampler.driver.jmeter.JMeterSampler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.service;
/**
* Manager available sampler types (JMeter, Gatling...)
* @since 1.0
*
*/
@Service
public class SamplerService implements InitializingBean{
| private Map<String,Sampler> samplers; |
centralperf/centralperf | src/main/java/org/centralperf/service/SamplerService.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
// @Deprecated
// public class GatlingSampler implements Sampler {
//
// @Resource
// private GatlingLauncher launcher;
//
// @Resource
// private GatlingScriptProcessor scriptProcessor;
//
// public static final String UID = "GATLING_1_X";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "Gatling 1.x";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".scala";
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
// @Component
// public class JMeterSampler implements Sampler {
//
// @Resource
// private JMeterLauncher launcher;
//
// @Resource
// private JMeterScriptProcessor scriptProcessor;
//
// public static final String UID = "JMETER_LOCAL";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "JMeter local";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".jmx";
// }
//
// }
| import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.driver.gatling.GatlingSampler;
import org.centralperf.sampler.driver.jmeter.JMeterSampler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.service;
/**
* Manager available sampler types (JMeter, Gatling...)
* @since 1.0
*
*/
@Service
public class SamplerService implements InitializingBean{
private Map<String,Sampler> samplers;
@Resource | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
// @Deprecated
// public class GatlingSampler implements Sampler {
//
// @Resource
// private GatlingLauncher launcher;
//
// @Resource
// private GatlingScriptProcessor scriptProcessor;
//
// public static final String UID = "GATLING_1_X";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "Gatling 1.x";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".scala";
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
// @Component
// public class JMeterSampler implements Sampler {
//
// @Resource
// private JMeterLauncher launcher;
//
// @Resource
// private JMeterScriptProcessor scriptProcessor;
//
// public static final String UID = "JMETER_LOCAL";
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getName() {
// return "JMeter local";
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getUID() {
// return UID;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerLauncher getLauncher() {
// return launcher;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public SamplerScriptProcessor getScriptProcessor() {
// return scriptProcessor;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String getScriptFileExtension() {
// return ".jmx";
// }
//
// }
// Path: src/main/java/org/centralperf/service/SamplerService.java
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.driver.gatling.GatlingSampler;
import org.centralperf.sampler.driver.jmeter.JMeterSampler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.service;
/**
* Manager available sampler types (JMeter, Gatling...)
* @since 1.0
*
*/
@Service
public class SamplerService implements InitializingBean{
private Map<String,Sampler> samplers;
@Resource | private JMeterSampler jMeterSampler; |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/jmeter/JMeterCSVReaderTimerTask.java | // Path: src/main/java/org/centralperf/helper/CSVHeaderInfo.java
// public class CSVHeaderInfo{
//
// /**
// * Name of the CSV header to use for sample execution date/time
// */
// public static final String CSV_HEADER_TIMESTAMP = "timestamp";
// /**
// * Name of the CSV header to use for elapsed time in ms
// */
// public static final String CSV_HEADER_ELAPSED = "elapsed";
// /**
// * Name of the CSV header to use for sample name
// */
// public static final String CSV_HEADER_SAMPLENAME = "label";
// /**
// * Name of the CSV header to use for sample result status
// */
// public static final String CSV_HEADER_STATUS = "responseMessage";
// /**
// * Name of the CSV header to use for sample response code (HTTP Response code for example)
// */
// public static final String CSV_HEADER_RESPONSECODE = "responsecode";
// /**
// * Name of the CSV header to use for assert result
// */
// public static final String CSV_HEADER_ASSERTRESULT = "success";
// /**
// * Name of the CSV header to use for sample size on bytes
// */
// public static final String CSV_HEADER_SIZEINBYTES = "bytes";
// /**
// * Name of the CSV header to use for number of users in group
// */
// public static final String CSV_HEADER_GROUPTHREADS = "grpthreads";
// /**
// * Name of the CSV header to use for number of all current users
// */
// public static final String CSV_HEADER_ALLTHREADS = "allthreads";
// /**
// * Name of the CSV header to use for latency
// */
// public static final String CSV_HEADER_LATENCY = "latency";
// /**
// * Name of the CSV header to use for CP sample id
// */
// public static final String CSV_HEADER_SAMPLEID = "sampleid";
// /**
// * Name of the CSV header to use for CP run id
// */
// public static final String CSV_HEADER_RUNID = "runid";
//
// private HashMap<String, Integer> headersIndex = new HashMap<String, Integer>();
//
// /**
// * Put the headers provided in a Hashmap for indexing
// * @param headers An array of CSV headers. ["myFirstHeader","mySecondHeader","anotherHeader","lastHeader"] for example.
// */
// public CSVHeaderInfo(String[] headers){
// for (int i=0; i<headers.length; i++){
// headersIndex.put(headers[i].trim().toLowerCase(), i);
// }
// }
//
// /**
// * Get the value for a specific field based on the associated headerName and a CSV line
// * @param headerName Name of the header for the value to find (column name)
// * @param CSVline The current line in the CSV file to analyse
// * @return The value associated to this header for the provided line
// */
// public String getValue(String headerName, String[] CSVline){
// try{
// return CSVline[headersIndex.get(headerName.toLowerCase())];
// }
// catch(ArrayIndexOutOfBoundsException aioobe){
// return null;
// }
// }
//
// }
| import org.centralperf.helper.CSVHeaderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* JMeterCSVReader reads JMeter CSV output file every seconds to extract
* data and push it the CSV Reader
*
* @since 1.0
*/
public class JMeterCSVReaderTimerTask extends TimerTask {
private JMeterCSVReader reader;
private static final Logger log = LoggerFactory.getLogger(JMeterCSVReaderTimerTask.class);
private File csvFile;
private long csvFileLastTimestamp;
private long csvFileLastLength;
private long nbSamples = 0;
| // Path: src/main/java/org/centralperf/helper/CSVHeaderInfo.java
// public class CSVHeaderInfo{
//
// /**
// * Name of the CSV header to use for sample execution date/time
// */
// public static final String CSV_HEADER_TIMESTAMP = "timestamp";
// /**
// * Name of the CSV header to use for elapsed time in ms
// */
// public static final String CSV_HEADER_ELAPSED = "elapsed";
// /**
// * Name of the CSV header to use for sample name
// */
// public static final String CSV_HEADER_SAMPLENAME = "label";
// /**
// * Name of the CSV header to use for sample result status
// */
// public static final String CSV_HEADER_STATUS = "responseMessage";
// /**
// * Name of the CSV header to use for sample response code (HTTP Response code for example)
// */
// public static final String CSV_HEADER_RESPONSECODE = "responsecode";
// /**
// * Name of the CSV header to use for assert result
// */
// public static final String CSV_HEADER_ASSERTRESULT = "success";
// /**
// * Name of the CSV header to use for sample size on bytes
// */
// public static final String CSV_HEADER_SIZEINBYTES = "bytes";
// /**
// * Name of the CSV header to use for number of users in group
// */
// public static final String CSV_HEADER_GROUPTHREADS = "grpthreads";
// /**
// * Name of the CSV header to use for number of all current users
// */
// public static final String CSV_HEADER_ALLTHREADS = "allthreads";
// /**
// * Name of the CSV header to use for latency
// */
// public static final String CSV_HEADER_LATENCY = "latency";
// /**
// * Name of the CSV header to use for CP sample id
// */
// public static final String CSV_HEADER_SAMPLEID = "sampleid";
// /**
// * Name of the CSV header to use for CP run id
// */
// public static final String CSV_HEADER_RUNID = "runid";
//
// private HashMap<String, Integer> headersIndex = new HashMap<String, Integer>();
//
// /**
// * Put the headers provided in a Hashmap for indexing
// * @param headers An array of CSV headers. ["myFirstHeader","mySecondHeader","anotherHeader","lastHeader"] for example.
// */
// public CSVHeaderInfo(String[] headers){
// for (int i=0; i<headers.length; i++){
// headersIndex.put(headers[i].trim().toLowerCase(), i);
// }
// }
//
// /**
// * Get the value for a specific field based on the associated headerName and a CSV line
// * @param headerName Name of the header for the value to find (column name)
// * @param CSVline The current line in the CSV file to analyse
// * @return The value associated to this header for the provided line
// */
// public String getValue(String headerName, String[] CSVline){
// try{
// return CSVline[headersIndex.get(headerName.toLowerCase())];
// }
// catch(ArrayIndexOutOfBoundsException aioobe){
// return null;
// }
// }
//
// }
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterCSVReaderTimerTask.java
import org.centralperf.helper.CSVHeaderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* JMeterCSVReader reads JMeter CSV output file every seconds to extract
* data and push it the CSV Reader
*
* @since 1.0
*/
public class JMeterCSVReaderTimerTask extends TimerTask {
private JMeterCSVReader reader;
private static final Logger log = LoggerFactory.getLogger(JMeterCSVReaderTimerTask.class);
private File csvFile;
private long csvFileLastTimestamp;
private long csvFileLastLength;
private long nbSamples = 0;
| private CSVHeaderInfo headerInfo; |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* @inheritDoc
*
* Jmeter based Sampler
*
* @since 1.0
*/
@Component
public class JMeterSampler implements Sampler {
@Resource
private JMeterLauncher launcher;
@Resource
private JMeterScriptProcessor scriptProcessor;
public static final String UID = "JMETER_LOCAL";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JMeter local";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* @inheritDoc
*
* Jmeter based Sampler
*
* @since 1.0
*/
@Component
public class JMeterSampler implements Sampler {
@Resource
private JMeterLauncher launcher;
@Resource
private JMeterScriptProcessor scriptProcessor;
public static final String UID = "JMETER_LOCAL";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JMeter local";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override | public SamplerLauncher getLauncher() { |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* @inheritDoc
*
* Jmeter based Sampler
*
* @since 1.0
*/
@Component
public class JMeterSampler implements Sampler {
@Resource
private JMeterLauncher launcher;
@Resource
private JMeterScriptProcessor scriptProcessor;
public static final String UID = "JMETER_LOCAL";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JMeter local";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override
public SamplerLauncher getLauncher() {
return launcher;
}
/**
* {@inheritDoc}
*/
@Override | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/JMeterSampler.java
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter;
/**
* @inheritDoc
*
* Jmeter based Sampler
*
* @since 1.0
*/
@Component
public class JMeterSampler implements Sampler {
@Resource
private JMeterLauncher launcher;
@Resource
private JMeterScriptProcessor scriptProcessor;
public static final String UID = "JMETER_LOCAL";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JMeter local";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override
public SamplerLauncher getLauncher() {
return launcher;
}
/**
* {@inheritDoc}
*/
@Override | public SamplerScriptProcessor getScriptProcessor() { |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/jmeter/helper/JMXScriptVariableExtractor.java | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter.helper;
/**
* Extract variables declared in a JMeter JMX file.
* Variables are locate in <Arguments tags.
* This class returns variables grouped by set (a set by Argument blocks)
* @since 1.0
*/
public class JMXScriptVariableExtractor {
private static final Logger log = LoggerFactory.getLogger(JMXScriptVariableExtractor.class);
/**
* Parse a JMX file to extract all variables declared in it
* @param jmxFile
* @return
* @throws FileNotFoundException
*/ | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
// Path: src/main/java/org/centralperf/sampler/driver/jmeter/helper/JMXScriptVariableExtractor.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.jmeter.helper;
/**
* Extract variables declared in a JMeter JMX file.
* Variables are locate in <Arguments tags.
* This class returns variables grouped by set (a set by Argument blocks)
* @since 1.0
*/
public class JMXScriptVariableExtractor {
private static final Logger log = LoggerFactory.getLogger(JMXScriptVariableExtractor.class);
/**
* Parse a JMX file to extract all variables declared in it
* @param jmxFile
* @return
* @throws FileNotFoundException
*/ | public static List<ScriptVariableSet> extractVariables(File jmxFile) throws FileNotFoundException { |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling 1.x based Sampler
* @since 1.0
*/
//@Component
@Deprecated
public class GatlingSampler implements Sampler {
@Resource
private GatlingLauncher launcher;
@Resource
private GatlingScriptProcessor scriptProcessor;
public static final String UID = "GATLING_1_X";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Gatling 1.x";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling 1.x based Sampler
* @since 1.0
*/
//@Component
@Deprecated
public class GatlingSampler implements Sampler {
@Resource
private GatlingLauncher launcher;
@Resource
private GatlingScriptProcessor scriptProcessor;
public static final String UID = "GATLING_1_X";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Gatling 1.x";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override | public SamplerLauncher getLauncher() { |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling 1.x based Sampler
* @since 1.0
*/
//@Component
@Deprecated
public class GatlingSampler implements Sampler {
@Resource
private GatlingLauncher launcher;
@Resource
private GatlingScriptProcessor scriptProcessor;
public static final String UID = "GATLING_1_X";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Gatling 1.x";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override
public SamplerLauncher getLauncher() {
return launcher;
}
/**
* {@inheritDoc}
*/
@Override | // Path: src/main/java/org/centralperf/sampler/api/Sampler.java
// public interface Sampler {
// /**
// * Human readable of the sampler
// * @return The name for this sampler
// */
// public String getName();
//
// /**
// * Arbitratry unique ID for this sampler. Will never be displayed, but we be used to identify the kind of sampler used for a run
// * @return The UID of this sampler
// */
// public String getUID();
//
// /**
// * Launcher for this sample
// * @return The launched of this sampler
// */
// public SamplerLauncher getLauncher();
//
// /**
// * The script processor analyze script to extract variables and is used to inject custom variables values in a definitive script
// * before being launched
// * @return The script processor for this sampler
// */
// public SamplerScriptProcessor getScriptProcessor();
//
// /**
// * Get the file extension for a script. This allows to build a complete filename when downloading the script
// * @return the script file common extension (".jmx" for example)
// */
// public String getScriptFileExtension();
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerLauncher.java
// public interface SamplerLauncher {
//
// /**
// * Launched the sampler and provides a job to interact with it
// * @param ScriptContent The script content to be used
// * @param run The run associated with this launch
// * @return A running job
// */
// public abstract SamplerRunJob launch(String ScriptContent, Run run) throws ConfigurationException;
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingSampler.java
import javax.annotation.Resource;
import org.centralperf.sampler.api.Sampler;
import org.centralperf.sampler.api.SamplerLauncher;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling 1.x based Sampler
* @since 1.0
*/
//@Component
@Deprecated
public class GatlingSampler implements Sampler {
@Resource
private GatlingLauncher launcher;
@Resource
private GatlingScriptProcessor scriptProcessor;
public static final String UID = "GATLING_1_X";
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "Gatling 1.x";
}
/**
* {@inheritDoc}
*/
@Override
public String getUID() {
return UID;
}
/**
* {@inheritDoc}
*/
@Override
public SamplerLauncher getLauncher() {
return launcher;
}
/**
* {@inheritDoc}
*/
@Override | public SamplerScriptProcessor getScriptProcessor() { |
centralperf/centralperf | src/main/java/org/centralperf/controller/ConfigurationController.java | // Path: src/main/java/org/centralperf/service/ConfigurationService.java
// @Service
// public class ConfigurationService {
//
// @Resource
// private KeyValueRepository keyValueRepository;
//
// @Autowired
// private AbstractBeanFactory beanFactory;
//
// private static final Logger log = LoggerFactory.getLogger(ConfigurationService.class);
//
// LoadingCache<String,Configuration> cache = CacheBuilder.newBuilder()
// .maximumSize(100)
// .build(new CacheLoader<String, Configuration>() {
// @Override
// public Configuration load(String key) throws Exception {
// log.debug("Value for ["+key+"] not in cache. Loading from DB and properties file");
// Configuration cnf = new Configuration(key);
//
// //First looking in DB
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue!=null){
// cnf.setFromDb(true);
// cnf.setKeyValue(keyValue.getValue());
// log.debug("Value for ["+key+"] found in database["+cnf.getKeyValue()+"].");
// }
// else{
// cnf.setFromDb(false);
// try{
// cnf.setKeyValue(beanFactory.resolveEmbeddedValue("${"+key+"}"));
// log.debug("Value for ["+key+"] found in properties["+cnf.getKeyValue()+"].");
// }
// catch(IllegalArgumentException e){
// // The key is not necessaraly in a property file. It may be possible to check properties that will exist at last only in the DB
// // Then set configuration to null
// log.debug("Value for ["+key+"] not found in properties. Set it to null.");
// cnf.setKeyValue(null);
// }
// }
// return cnf;
// }
// });
//
//
// public Configuration getConfigurationData(String key){
// return cache.getUnchecked(key);
// }
//
// public String getConfigurationValue(String key){
// return cache.getUnchecked(key).getKeyValue();
// }
//
// public void updateConfigurationValue(String key, String value){
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue == null){
// keyValue = new KeyValue();
// keyValue.setKey(key);
// }
// keyValue.setValue(value);
// log.warn("Updating ["+keyValue.getKey()+"] with data ["+keyValue.getValue()+"] in db");
// keyValueRepository.save(keyValue);
// log.warn("Invalidation of ["+keyValue.getKey()+"] from cache");
// cache.invalidate(key);
// }
//
// public void deleteConfigurationValue(String key){
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue!=null){
// keyValueRepository.delete(keyValue);
// cache.invalidate(key);
// }
// else{log.warn("Revert of ["+key+"] could not be done (Was not found in DB");}
// }
// }
| import javax.annotation.Resource;
import org.centralperf.service.ConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.controller;
/**
* The Configuration controller is used to allow en user interaction with CP configuration through the Web interface
* @since 1.0
*/
@Controller
public class ConfigurationController {
private static final Logger log = LoggerFactory.getLogger(ConfigurationController.class);
@Resource | // Path: src/main/java/org/centralperf/service/ConfigurationService.java
// @Service
// public class ConfigurationService {
//
// @Resource
// private KeyValueRepository keyValueRepository;
//
// @Autowired
// private AbstractBeanFactory beanFactory;
//
// private static final Logger log = LoggerFactory.getLogger(ConfigurationService.class);
//
// LoadingCache<String,Configuration> cache = CacheBuilder.newBuilder()
// .maximumSize(100)
// .build(new CacheLoader<String, Configuration>() {
// @Override
// public Configuration load(String key) throws Exception {
// log.debug("Value for ["+key+"] not in cache. Loading from DB and properties file");
// Configuration cnf = new Configuration(key);
//
// //First looking in DB
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue!=null){
// cnf.setFromDb(true);
// cnf.setKeyValue(keyValue.getValue());
// log.debug("Value for ["+key+"] found in database["+cnf.getKeyValue()+"].");
// }
// else{
// cnf.setFromDb(false);
// try{
// cnf.setKeyValue(beanFactory.resolveEmbeddedValue("${"+key+"}"));
// log.debug("Value for ["+key+"] found in properties["+cnf.getKeyValue()+"].");
// }
// catch(IllegalArgumentException e){
// // The key is not necessaraly in a property file. It may be possible to check properties that will exist at last only in the DB
// // Then set configuration to null
// log.debug("Value for ["+key+"] not found in properties. Set it to null.");
// cnf.setKeyValue(null);
// }
// }
// return cnf;
// }
// });
//
//
// public Configuration getConfigurationData(String key){
// return cache.getUnchecked(key);
// }
//
// public String getConfigurationValue(String key){
// return cache.getUnchecked(key).getKeyValue();
// }
//
// public void updateConfigurationValue(String key, String value){
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue == null){
// keyValue = new KeyValue();
// keyValue.setKey(key);
// }
// keyValue.setValue(value);
// log.warn("Updating ["+keyValue.getKey()+"] with data ["+keyValue.getValue()+"] in db");
// keyValueRepository.save(keyValue);
// log.warn("Invalidation of ["+keyValue.getKey()+"] from cache");
// cache.invalidate(key);
// }
//
// public void deleteConfigurationValue(String key){
// KeyValue keyValue = keyValueRepository.findByKey(key);
// if(keyValue!=null){
// keyValueRepository.delete(keyValue);
// cache.invalidate(key);
// }
// else{log.warn("Revert of ["+key+"] could not be done (Was not found in DB");}
// }
// }
// Path: src/main/java/org/centralperf/controller/ConfigurationController.java
import javax.annotation.Resource;
import org.centralperf.service.ConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.controller;
/**
* The Configuration controller is used to allow en user interaction with CP configuration through the Web interface
* @since 1.0
*/
@Controller
public class ConfigurationController {
private static final Logger log = LoggerFactory.getLogger(ConfigurationController.class);
@Resource | private ConfigurationService configurationService; |
centralperf/centralperf | src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
| import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.api;
/**
* A Processor handle all operations on script
* @since 1.0
*/
public interface SamplerScriptProcessor {
/**
* Validates the provided script is compatible with this sampler
* @param script
* @return true if script is compatible
*/
public boolean validateScript(String script);
/**
* Get the variables for provided script
* @param script
* @return a list of variable sets
*/ | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.api;
/**
* A Processor handle all operations on script
* @since 1.0
*/
public interface SamplerScriptProcessor {
/**
* Validates the provided script is compatible with this sampler
* @param script
* @return true if script is compatible
*/
public boolean validateScript(String script);
/**
* Get the variables for provided script
* @param script
* @return a list of variable sets
*/ | public List<ScriptVariableSet> getVariableSets(String script); |
centralperf/centralperf | src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
| import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.api;
/**
* A Processor handle all operations on script
* @since 1.0
*/
public interface SamplerScriptProcessor {
/**
* Validates the provided script is compatible with this sampler
* @param script
* @return true if script is compatible
*/
public boolean validateScript(String script);
/**
* Get the variables for provided script
* @param script
* @return a list of variable sets
*/
public List<ScriptVariableSet> getVariableSets(String script);
/**
* Returns a script with variables replaced with provided values
* @param scriptContent
* @param scriptVariables
* @return
*/ | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.api;
/**
* A Processor handle all operations on script
* @since 1.0
*/
public interface SamplerScriptProcessor {
/**
* Validates the provided script is compatible with this sampler
* @param script
* @return true if script is compatible
*/
public boolean validateScript(String script);
/**
* Get the variables for provided script
* @param script
* @return a list of variable sets
*/
public List<ScriptVariableSet> getVariableSets(String script);
/**
* Returns a script with variables replaced with provided values
* @param scriptContent
* @param scriptVariables
* @return
*/ | public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables); |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/gatling/GatlingScriptProcessor.java | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling based Script processor
* @since 1.0
*/
@Component
public class GatlingScriptProcessor implements SamplerScriptProcessor {
@Override
public boolean validateScript(String script) {
return script.startsWith("package");
}
@Override | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingScriptProcessor.java
import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling based Script processor
* @since 1.0
*/
@Component
public class GatlingScriptProcessor implements SamplerScriptProcessor {
@Override
public boolean validateScript(String script) {
return script.startsWith("package");
}
@Override | public List<ScriptVariableSet> getVariableSets(String script) { |
centralperf/centralperf | src/main/java/org/centralperf/sampler/driver/gatling/GatlingScriptProcessor.java | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
| import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling based Script processor
* @since 1.0
*/
@Component
public class GatlingScriptProcessor implements SamplerScriptProcessor {
@Override
public boolean validateScript(String script) {
return script.startsWith("package");
}
@Override
public List<ScriptVariableSet> getVariableSets(String script) {
return null;
}
@Override
public String replaceVariablesInScript(String scriptContent, | // Path: src/main/java/org/centralperf/model/dao/ScriptVariable.java
// @Entity
// public class ScriptVariable {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
// private String defaultValue;
// private String value;
// private String description;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getDefaultValue() {
// return defaultValue;
// }
// public void setDefaultValue(String defaultValue) {
// this.defaultValue = defaultValue;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public ScriptVariable clone() {
// ScriptVariable scriptVariable = new ScriptVariable();
// scriptVariable.setName(this.getName());
// scriptVariable.setValue(this.getValue());
// scriptVariable.setDescription(this.getDescription());
// scriptVariable.setDefaultValue(this.getDefaultValue());
// return scriptVariable;
// };
//
// @Override
// public String toString() {
// return "ScriptVariable. Name = " + this.getName()
// + ", value = " + this.getValue()
// + ", default value = " + this.getDefaultValue()
// + ", description = " + this.getDescription();
// }
//
// }
//
// Path: src/main/java/org/centralperf/model/dao/ScriptVariableSet.java
// @Entity
// public class ScriptVariableSet {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String name;
//
// @OneToMany(cascade=CascadeType.ALL)
// private List<ScriptVariable> scriptVariables = new ArrayList<ScriptVariable>();
//
// public List<ScriptVariable> getScriptVariables() {
// return scriptVariables;
// }
// public void setScriptVariables(List<ScriptVariable> scriptsVariable) {
// this.scriptVariables = scriptsVariable;
// }
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("Script variable set. Name = " + this.getName() + "\r\n");
// builder.append("==================\r\n");
// for (ScriptVariable scriptsVariable : this.getScriptVariables()) {
// builder.append(scriptsVariable.toString() + "\r\n");
// }
// builder.append("==================\r\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/org/centralperf/sampler/api/SamplerScriptProcessor.java
// public interface SamplerScriptProcessor {
//
// /**
// * Validates the provided script is compatible with this sampler
// * @param script
// * @return true if script is compatible
// */
// public boolean validateScript(String script);
//
// /**
// * Get the variables for provided script
// * @param script
// * @return a list of variable sets
// */
// public List<ScriptVariableSet> getVariableSets(String script);
//
// /**
// * Returns a script with variables replaced with provided values
// * @param scriptContent
// * @param scriptVariables
// * @return
// */
// public String replaceVariablesInScript(String scriptContent,List<ScriptVariable> scriptVariables);
// }
// Path: src/main/java/org/centralperf/sampler/driver/gatling/GatlingScriptProcessor.java
import java.util.List;
import org.centralperf.model.dao.ScriptVariable;
import org.centralperf.model.dao.ScriptVariableSet;
import org.centralperf.sampler.api.SamplerScriptProcessor;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.sampler.driver.gatling;
/**
* Gatling based Script processor
* @since 1.0
*/
@Component
public class GatlingScriptProcessor implements SamplerScriptProcessor {
@Override
public boolean validateScript(String script) {
return script.startsWith("package");
}
@Override
public List<ScriptVariableSet> getVariableSets(String script) {
return null;
}
@Override
public String replaceVariablesInScript(String scriptContent, | List<ScriptVariable> scriptVariables) { |
centralperf/centralperf | src/main/java/org/centralperf/model/dao/Run.java | // Path: src/main/java/org/centralperf/model/SampleDataBackendTypeEnum.java
// public enum SampleDataBackendTypeEnum {
// /**
// * Central Perf database
// */
// DEFAULT,
// /**
// * Elastic Search cluster
// */
// ES
// }
| import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.centralperf.model.SampleDataBackendTypeEnum;
import org.hibernate.annotations.Type; | /*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.model.dao;
/**
* A run is based on a script (specific version) associated with custom variable values (number of users, duration....)
* A run may ready to be launched, running or achieved. An already launched run cannot be launched again (in fact you can, but a new run is then created)
* This is an Entity bean to persist Run info into the persistence layer.
*
* @since 1.0
*/
@Entity
public class Run {
@Id
@GeneratedValue
private Long id;
@NotNull
@Size(min = 1, max = 33)
private String label;
@ManyToOne
private ScriptVersion scriptVersion;
private boolean launched = false;
private boolean running = false;
private Date startDate;
private Date endDate;
private String comment;
@OneToMany(cascade=CascadeType.ALL)
private List<ScriptVariable> customScriptVariables = new ArrayList<ScriptVariable>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "projectId")
private Project project;
@Lob
@Column( length = 1000000 )
@Type(type="text")
private String processOutput;
@OneToMany(mappedBy="run", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Sample> samples;
| // Path: src/main/java/org/centralperf/model/SampleDataBackendTypeEnum.java
// public enum SampleDataBackendTypeEnum {
// /**
// * Central Perf database
// */
// DEFAULT,
// /**
// * Elastic Search cluster
// */
// ES
// }
// Path: src/main/java/org/centralperf/model/dao/Run.java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.centralperf.model.SampleDataBackendTypeEnum;
import org.hibernate.annotations.Type;
/*
* Copyright (C) 2014 The Central Perf authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.centralperf.model.dao;
/**
* A run is based on a script (specific version) associated with custom variable values (number of users, duration....)
* A run may ready to be launched, running or achieved. An already launched run cannot be launched again (in fact you can, but a new run is then created)
* This is an Entity bean to persist Run info into the persistence layer.
*
* @since 1.0
*/
@Entity
public class Run {
@Id
@GeneratedValue
private Long id;
@NotNull
@Size(min = 1, max = 33)
private String label;
@ManyToOne
private ScriptVersion scriptVersion;
private boolean launched = false;
private boolean running = false;
private Date startDate;
private Date endDate;
private String comment;
@OneToMany(cascade=CascadeType.ALL)
private List<ScriptVariable> customScriptVariables = new ArrayList<ScriptVariable>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "projectId")
private Project project;
@Lob
@Column( length = 1000000 )
@Type(type="text")
private String processOutput;
@OneToMany(mappedBy="run", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Sample> samples;
| private SampleDataBackendTypeEnum sampleDataBackendType = SampleDataBackendTypeEnum.DEFAULT; |
roys/java-hdl-webserver | src/main/java/com/roysolberg/java/hdlserver/util/HdlUtil.java | // Path: src/main/java/com/roysolberg/java/hdlserver/hdl/component/HdlComponent.java
// public abstract class HdlComponent implements Serializable{
//
// protected int subnet; // 0-254
// protected int deviceId; // 0-254
// protected int deviceType; // 0-65535 // TODO: Why do we use both "device" and "component" for the same thing?
// protected String remark;
//
// public HdlComponent(int subnet, int deviceId, int deviceType, String remark) {
// this.subnet = subnet;
// this.deviceId = deviceId;
// this.deviceType = deviceType;
// this.remark = getCleanRemark(remark);
// }
//
// protected String getCleanRemark(String remark) {
// if (remark != null) {
// remark = remark.replaceAll("\u0000", "");
// }
// return remark;
// }
//
// public int getSubnet() {
// return subnet;
// }
//
// public void setSubnet(int subnet) {
// this.subnet = subnet;
// }
//
// public int getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(int deviceId) {
// this.deviceId = deviceId;
// }
//
// public int getDeviceType() {
// return deviceType;
// }
//
// public void setDeviceType(int deviceType) {
// this.deviceType = deviceType;
// }
//
// public abstract String getDeviceGroup();
//
// public String getRemark() {
// return remark;
// }
//
// public void setDescription(String remark) {
// this.remark = remark;
// }
//
// public abstract String getDescription();
//
// public abstract int getDefaultSortOrder();
//
// @Override
// public String toString() {
// return "HdlComponent[remark:" + remark + ",description:" + getDescription() + ",type:" + deviceType + ",subnet:" + subnet + ",device:" + deviceId + "]";
// }
//
// }
| import com.roysolberg.java.hdlserver.hdl.component.HdlComponent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Arrays; | case 0xE3DA:
return "Read panel status";
case 0xE3DB:
return "Response read panel status";
case 55808: // 0xDA00
return "Read system date and time";
case 55809: // 0xDA01
return "Response read system date and time";
case 55876: // 0xDA44
return "Broadcast system date and time (every minute)";
case 58341: // 0xE3E5
return "Broadcast temperature";
case 61439: // 0xEFFF
return "Broadcast status of scene";
case 61494: // 0xF036
return "Broadcast status of sequence";
case 0xF037:
return "Read IP module config";
case 0xF038:
return "Response read IP module config";
default:
return "Unknown operation";
}
}
public static String getNiceOperationCode(byte[] bytes) {
int operationCode = (bytes[BYTE_POSITION_OPERATION_CODE_BYTE_2] & 0xFF) | (bytes[BYTE_POSITION_OPERATION_CODE_BYTE_1] & 0xFF) << 8;
return getNiceOperationCode(operationCode);
}
| // Path: src/main/java/com/roysolberg/java/hdlserver/hdl/component/HdlComponent.java
// public abstract class HdlComponent implements Serializable{
//
// protected int subnet; // 0-254
// protected int deviceId; // 0-254
// protected int deviceType; // 0-65535 // TODO: Why do we use both "device" and "component" for the same thing?
// protected String remark;
//
// public HdlComponent(int subnet, int deviceId, int deviceType, String remark) {
// this.subnet = subnet;
// this.deviceId = deviceId;
// this.deviceType = deviceType;
// this.remark = getCleanRemark(remark);
// }
//
// protected String getCleanRemark(String remark) {
// if (remark != null) {
// remark = remark.replaceAll("\u0000", "");
// }
// return remark;
// }
//
// public int getSubnet() {
// return subnet;
// }
//
// public void setSubnet(int subnet) {
// this.subnet = subnet;
// }
//
// public int getDeviceId() {
// return deviceId;
// }
//
// public void setDeviceId(int deviceId) {
// this.deviceId = deviceId;
// }
//
// public int getDeviceType() {
// return deviceType;
// }
//
// public void setDeviceType(int deviceType) {
// this.deviceType = deviceType;
// }
//
// public abstract String getDeviceGroup();
//
// public String getRemark() {
// return remark;
// }
//
// public void setDescription(String remark) {
// this.remark = remark;
// }
//
// public abstract String getDescription();
//
// public abstract int getDefaultSortOrder();
//
// @Override
// public String toString() {
// return "HdlComponent[remark:" + remark + ",description:" + getDescription() + ",type:" + deviceType + ",subnet:" + subnet + ",device:" + deviceId + "]";
// }
//
// }
// Path: src/main/java/com/roysolberg/java/hdlserver/util/HdlUtil.java
import com.roysolberg.java.hdlserver.hdl.component.HdlComponent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Arrays;
case 0xE3DA:
return "Read panel status";
case 0xE3DB:
return "Response read panel status";
case 55808: // 0xDA00
return "Read system date and time";
case 55809: // 0xDA01
return "Response read system date and time";
case 55876: // 0xDA44
return "Broadcast system date and time (every minute)";
case 58341: // 0xE3E5
return "Broadcast temperature";
case 61439: // 0xEFFF
return "Broadcast status of scene";
case 61494: // 0xF036
return "Broadcast status of sequence";
case 0xF037:
return "Read IP module config";
case 0xF038:
return "Response read IP module config";
default:
return "Unknown operation";
}
}
public static String getNiceOperationCode(byte[] bytes) {
int operationCode = (bytes[BYTE_POSITION_OPERATION_CODE_BYTE_2] & 0xFF) | (bytes[BYTE_POSITION_OPERATION_CODE_BYTE_1] & 0xFF) << 8;
return getNiceOperationCode(operationCode);
}
| public static String getNicelyDescribedBytes(byte[] bytes, HdlComponent hdlComponent) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java | // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
| import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer; | package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
| // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
// Path: src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java
import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer;
package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
| public GeneralsApi onConnected(NoArgsListener listener) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java | // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
| import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer; | package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
public GeneralsApi onConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent());
}
public GeneralsApi onceConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent(), true);
}
public GeneralsApi onDisconnected(NoArgsListener listener) {
return onEvent("disconnect", (args) -> listener.onEvent());
}
| // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
// Path: src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java
import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer;
package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
public GeneralsApi onConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent());
}
public GeneralsApi onceConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent(), true);
}
public GeneralsApi onDisconnected(NoArgsListener listener) {
return onEvent("disconnect", (args) -> listener.onEvent());
}
| public GeneralsApi onGameStarted(OneArgListener<GameStartApiResponse> listener) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java | // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
| import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer; | package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
public GeneralsApi onConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent());
}
public GeneralsApi onceConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent(), true);
}
public GeneralsApi onDisconnected(NoArgsListener listener) {
return onEvent("disconnect", (args) -> listener.onEvent());
}
public GeneralsApi onGameStarted(OneArgListener<GameStartApiResponse> listener) {
return onEvent("game_start", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameStartApiResponse.class)));
}
public GeneralsApi onGameUpdated(OneArgListener<GameUpdateApiResponse> listener) {
return onEvent("game_update", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameUpdateApiResponse.class)));
}
public GeneralsApi onGameLost(OneArgListener<GameLostApiResponse> listener) {
return onEvent("game_lost", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameLostApiResponse.class)));
}
public GeneralsApi onGameWon(NoArgsListener listener) {
return onEvent("game_won", (args) -> listener.onEvent());
}
| // Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
// @FunctionalInterface
// public interface ChatMessageListener {
// void onEvent(String chatRoom, ChatMessageApiResponse message);
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/NoArgsListener.java
// @FunctionalInterface
// public interface NoArgsListener {
// void onEvent();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/listener/OneArgListener.java
// @FunctionalInterface
// public interface OneArgListener<T> {
// void onEvent(T event);
// }
// Path: src/main/java/pl/joegreen/sergeants/api/GeneralsApi.java
import pl.joegreen.sergeants.api.listener.ChatMessageListener;
import pl.joegreen.sergeants.api.listener.NoArgsListener;
import pl.joegreen.sergeants.api.listener.OneArgListener;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.joegreen.sergeants.api.response.*;
import java.util.Arrays;
import java.util.function.Consumer;
package pl.joegreen.sergeants.api;
public class GeneralsApi {
private static final String ONE_VS_ONE_QUEUE = "1v1";
private static final String TWO_VS_TWO_QUEUE = "2v2";
private static final String FFA_QUEUE = "";
private static final Logger LOGGER = LoggerFactory.getLogger(GeneralsApi.class);
private Socket socket;
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new JsonOrgModule());
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
private GeneralsApi(Socket socket) {
this.socket = socket;
}
public static GeneralsApi create() {
return new GeneralsApi(new RealSocket());
}
/**
* For testing purposes.
*/
public static GeneralsApi createWithCustomSocket(Socket socket) {
return new GeneralsApi(socket);
}
public boolean isConnected() {
return socket.connected();
}
/* LISTENERS */
public GeneralsApi onEvent(String event, Consumer<Object[]> listener, boolean onlyOnce) {
Consumer<Object[]> socketListener = args -> {
LOGGER.trace("Received {}: {}", event, Arrays.toString(args));
listener.accept(args);
};
if (onlyOnce) {
socket.once(event, socketListener);
} else {
socket.on(event, socketListener);
}
return this;
}
public GeneralsApi onEvent(String event, Consumer<Object[]> listener) {
return onEvent(event, listener, false);
}
public GeneralsApi onConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent());
}
public GeneralsApi onceConnected(NoArgsListener listener) {
return onEvent("connect", (args) -> listener.onEvent(), true);
}
public GeneralsApi onDisconnected(NoArgsListener listener) {
return onEvent("disconnect", (args) -> listener.onEvent());
}
public GeneralsApi onGameStarted(OneArgListener<GameStartApiResponse> listener) {
return onEvent("game_start", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameStartApiResponse.class)));
}
public GeneralsApi onGameUpdated(OneArgListener<GameUpdateApiResponse> listener) {
return onEvent("game_update", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameUpdateApiResponse.class)));
}
public GeneralsApi onGameLost(OneArgListener<GameLostApiResponse> listener) {
return onEvent("game_lost", (args) -> listener.onEvent(objectMapper.convertValue(args[0], GameLostApiResponse.class)));
}
public GeneralsApi onGameWon(NoArgsListener listener) {
return onEvent("game_won", (args) -> listener.onEvent());
}
| public GeneralsApi onChatMessage(ChatMessageListener listener) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/MountainTile.java | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_MOUNTAIN = new TerrainType(-2);
| import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_MOUNTAIN; | package pl.joegreen.sergeants.simulator;
class MountainTile extends AbstractTile {
MountainTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_MOUNTAIN = new TerrainType(-2);
// Path: src/main/java/pl/joegreen/sergeants/simulator/MountainTile.java
import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_MOUNTAIN;
package pl.joegreen.sergeants.simulator;
class MountainTile extends AbstractTile {
MountainTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | return visible ? TILE_MOUNTAIN : TILE_FOG_OBSTACLE; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/MountainTile.java | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_MOUNTAIN = new TerrainType(-2);
| import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_MOUNTAIN; | package pl.joegreen.sergeants.simulator;
class MountainTile extends AbstractTile {
MountainTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_MOUNTAIN = new TerrainType(-2);
// Path: src/main/java/pl/joegreen/sergeants/simulator/MountainTile.java
import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_MOUNTAIN;
package pl.joegreen.sergeants.simulator;
class MountainTile extends AbstractTile {
MountainTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | return visible ? TILE_MOUNTAIN : TILE_FOG_OBSTACLE; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/EmptyTile.java | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG = new TerrainType(-3);
| import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG; | package pl.joegreen.sergeants.simulator;
class EmptyTile extends AbstractTile {
EmptyTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG = new TerrainType(-3);
// Path: src/main/java/pl/joegreen/sergeants/simulator/EmptyTile.java
import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG;
package pl.joegreen.sergeants.simulator;
class EmptyTile extends AbstractTile {
EmptyTile(int tileIndex) {
super(tileIndex);
}
@Override
public TerrainType getTerrainType(boolean visible) { | return visible ? getOwnerPlayerIndex().map(TerrainType::playerOwnedTerrain).orElse(TerrainType.TILE_EMPTY) : TILE_FOG; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
| import lombok.Value;
import pl.joegreen.sergeants.framework.model.Position; | package pl.joegreen.sergeants.simulator.viewer;
@Value
public class ViewerField { | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
import lombok.Value;
import pl.joegreen.sergeants.framework.model.Position;
package pl.joegreen.sergeants.simulator.viewer;
@Value
public class ViewerField { | Position position; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/GameMap.java | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
| import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; |
private Optional<Tile> getTileBelow(Tile tile) {
int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
| // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/GameMap.java
import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
private Optional<Tile> getTileBelow(Tile tile) {
int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
| public static ViewerMapState toViewerMapState(GameMap map) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/GameMap.java | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
| import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | private Optional<Tile> getTileBelow(Tile tile) {
int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
public static ViewerMapState toViewerMapState(GameMap map) { | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/GameMap.java
import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
private Optional<Tile> getTileBelow(Tile tile) {
int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
public static ViewerMapState toViewerMapState(GameMap map) { | Set<ViewerField> viewerFields = Arrays.stream(map.getTiles()).map( |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/GameMap.java | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
| import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
public static ViewerMapState toViewerMapState(GameMap map) {
Set<ViewerField> viewerFields = Arrays.stream(map.getTiles()).map( | // Path: src/main/java/pl/joegreen/sergeants/framework/model/Position.java
// @Value
// @Wither
// public class Position {
// int row;
// int col;
//
// public static Position fromIndex(int index, int columns) {
// return new Position(index / columns, index % columns);
// }
//
// public int toIndex(int columns) {
// return getCol() + getRow() * columns;
// }
//
// public boolean isVisibleFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) <= 1 && Math.abs(col - otherPosition.col) <= 1;
// }
//
// public boolean isMovableFrom(Position otherPosition) {
// return Math.abs(row - otherPosition.row) + Math.abs(col - otherPosition.col) == 1;
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerField.java
// @Value
// public class ViewerField {
// Position position;
// Integer owner;
// int army;
// boolean city;
// boolean general;
// boolean mountain;
//
// public String serializeToString() {
// StringBuilder builder = new StringBuilder();
// if (army > 0) {
// builder.append(army);
// }
// if (city) {
// builder.append("c");
// }
// if (general) {
// builder.append("g");
// }
// if (mountain) {
// builder.append("m");
// }
// if (owner != null) {
// builder.append("o").append(owner);
// }
// return builder.toString();
// }
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/ViewerMapState.java
// @Value
// public class ViewerMapState {
// int tick;
// int height;
// int width;
// Set<ViewerField> fields;
//
// public String serializeToString(){
// StringBuilder builder = new StringBuilder();
// builder.append(tick);
// builder.append(";").append(height).append(";").append(width).append(";");
// Comparator<ViewerField> orderComparator = Comparator.<ViewerField, Integer>comparing(vf -> vf.getPosition().getRow()).thenComparing(vf -> vf.getPosition().getCol());
// String fields = this.fields.stream().sorted(orderComparator).map(ViewerField::serializeToString).collect(Collectors.joining("|"));
// builder.append(fields);
// return builder.toString();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/GameMap.java
import pl.joegreen.sergeants.framework.model.Position;
import pl.joegreen.sergeants.simulator.viewer.ViewerField;
import pl.joegreen.sergeants.simulator.viewer.ViewerMapState;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
int tileIndex = tile.getTileIndex() + width;
return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
}
private Optional<Tile> getTileRightOf(Tile tile) {
boolean isMostRight = tile.getTileIndex() % width == width - 1;
return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
}
private Optional<Tile> getTileLeftOf(Tile tile) {
int tileIndex = tile.getTileIndex();
boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
}
int getHalfTurnCounter() {
return halfTurnCounter;
}
int getHeight() {
return height;
}
int getWidth() {
return width;
}
public static ViewerMapState toViewerMapState(GameMap map) {
Set<ViewerField> viewerFields = Arrays.stream(map.getTiles()).map( | tile -> new ViewerField(Position.fromIndex(tile.getTileIndex(), map.getWidth()), |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/Player.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
| import pl.joegreen.sergeants.framework.Bot;
import pl.joegreen.sergeants.framework.model.GameState;
import java.util.Deque; | package pl.joegreen.sergeants.simulator;
class Player {
private final String name;
private final int playerIndex; | // Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/Player.java
import pl.joegreen.sergeants.framework.Bot;
import pl.joegreen.sergeants.framework.model.GameState;
import java.util.Deque;
package pl.joegreen.sergeants.simulator;
class Player {
private final String name;
private final int playerIndex; | private final Bot bot; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/Player.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
| import pl.joegreen.sergeants.framework.Bot;
import pl.joegreen.sergeants.framework.model.GameState;
import java.util.Deque; | package pl.joegreen.sergeants.simulator;
class Player {
private final String name;
private final int playerIndex;
private final Bot bot;
private final Deque<Move> moves; | // Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/Player.java
import pl.joegreen.sergeants.framework.Bot;
import pl.joegreen.sergeants.framework.model.GameState;
import java.util.Deque;
package pl.joegreen.sergeants.simulator;
class Player {
private final String name;
private final int playerIndex;
private final Bot bot;
private final Deque<Move> moves; | private GameState gameState; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
| import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration; | package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration;
package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs | public static Simulator of(GameMap gameMap, Function<Actions, Bot>... botProviders) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
| import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration; | package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration;
package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs | public static Simulator of(GameMap gameMap, Function<Actions, Bot>... botProviders) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
| import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration; | package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs
public static Simulator of(GameMap gameMap, Function<Actions, Bot>... botProviders) { | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/Bot.java
// public interface Bot {
//
// /**
// * Called on every game state update from server.
// * @param newGameState Contains current state of the game.
// */
// default void onGameStateUpdate(GameState newGameState) {
// getLogger(Bot.class).info("Received new game state: " + newGameState.toString());
// }
//
// /**
// * Called when game is won, lost or the connection to the server is lost.
// * @param gameResult Result of the game.
// */
// default void onGameFinished(GameResult gameResult) {
// getLogger(Bot.class).info("Game finished, result: " + gameResult);
// }
//
// /**
// * Called when the new game is started.
// * @param gameStarted Contains basic info about the game (replay id, players in the game).
// */
// default void onGameStarted(GameStarted gameStarted) {
// getLogger(Bot.class).info("Game started: " + gameStarted);
// }
//
// /**
// * Called on every chat message (game chat, team chat)
// */
// default void onChatMessage(ChatMessage chatMessage){
// getLogger(Bot.class).info("Chat message: " + chatMessage);
// }
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorFactory.java
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.Bot;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.function.Function;
import java.util.stream.IntStream;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration;
package pl.joegreen.sergeants.simulator;
/**
* Factory class for creating simulations
*/
public class SimulatorFactory {
private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@SafeVarargs
public static Simulator of(GameMap gameMap, Function<Actions, Bot>... botProviders) { | return of(gameMap, configuration(), botProviders); |
greenjoe/sergeants | src/test/java/pl/joegreen/sergeants/simulator/SimulatorFullGameTest.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
| import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.*;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration; | package pl.joegreen.sergeants.simulator;
public class SimulatorFullGameTest {
@Test
public void testFullGame() {
Tile[] tiles = new Tile[]{
new GeneralTile(0, 0), new CityTile(1, 11), new MountainTile(2),
new EmptyTile(3), new EmptyTile(4), new EmptyTile(5),
new EmptyTile(6), new EmptyTile(7), new GeneralTile(8, 1)
};
GameMap gameMap = new GameMap(tiles, 3, 3);
BotInstanceCatcher<AttackGeneralBot> attackGeneralBotProvider = new BotInstanceCatcher<>(AttackGeneralBot::new); | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
// Path: src/test/java/pl/joegreen/sergeants/simulator/SimulatorFullGameTest.java
import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.*;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration;
package pl.joegreen.sergeants.simulator;
public class SimulatorFullGameTest {
@Test
public void testFullGame() {
Tile[] tiles = new Tile[]{
new GeneralTile(0, 0), new CityTile(1, 11), new MountainTile(2),
new EmptyTile(3), new EmptyTile(4), new EmptyTile(5),
new EmptyTile(6), new EmptyTile(7), new GeneralTile(8, 1)
};
GameMap gameMap = new GameMap(tiles, 3, 3);
BotInstanceCatcher<AttackGeneralBot> attackGeneralBotProvider = new BotInstanceCatcher<>(AttackGeneralBot::new); | Simulator server = SimulatorFactory.of(gameMap, configuration().withMaxTurns(200), DoSameMoveBot.forMove(0, 3), attackGeneralBotProvider); |
greenjoe/sergeants | src/test/java/pl/joegreen/sergeants/simulator/SimulatorFullGameTest.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
| import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.*;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration; | private void checkAttackGameBotStateTurn24(GameState gameState) {
assertEquals(24, gameState.getTurn());
VisibleField enemyGeneral = gameState.getTwoDimensionalArrayOfFields()[0][0].asVisibleField();
VisibleField city = gameState.getTwoDimensionalArrayOfFields()[0][1].asVisibleField();
VisibleField mountain = gameState.getTwoDimensionalArrayOfFields()[0][2].asVisibleField();
Assert.assertTrue(enemyGeneral.isGeneral());
Assert.assertTrue(city.isCity());
assertEquals(FieldTerrainType.MOUNTAIN, mountain.getTerrainType());
}
private void checkFinalGameState(Tile[] tiles) {
assertEquals(CityTile.class, tiles[0].getClass());
assertEquals(8, tiles[0].getArmySize());
assertEquals(Optional.of(1), tiles[0].getOwnerPlayerIndex());
assertEquals(CityTile.class, tiles[1].getClass());
assertEquals(2, tiles[1].getArmySize());
assertEquals(Optional.of(1), tiles[1].getOwnerPlayerIndex());
assertEquals(EmptyTile.class, tiles[3].getClass());
assertEquals(12, tiles[3].getArmySize());
assertEquals(Optional.of(1), tiles[3].getOwnerPlayerIndex());
assertEquals(GeneralTile.class, tiles[8].getClass());
assertEquals(3, tiles[8].getArmySize());
assertEquals(Optional.of(1), tiles[8].getOwnerPlayerIndex());
}
private class AttackGeneralBot extends TestBot { | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/simulator/SimulatorConfiguration.java
// public static SimulatorConfiguration configuration() {
// return new SimulatorConfiguration();
// }
// Path: src/test/java/pl/joegreen/sergeants/simulator/SimulatorFullGameTest.java
import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.*;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static pl.joegreen.sergeants.simulator.SimulatorConfiguration.configuration;
private void checkAttackGameBotStateTurn24(GameState gameState) {
assertEquals(24, gameState.getTurn());
VisibleField enemyGeneral = gameState.getTwoDimensionalArrayOfFields()[0][0].asVisibleField();
VisibleField city = gameState.getTwoDimensionalArrayOfFields()[0][1].asVisibleField();
VisibleField mountain = gameState.getTwoDimensionalArrayOfFields()[0][2].asVisibleField();
Assert.assertTrue(enemyGeneral.isGeneral());
Assert.assertTrue(city.isCity());
assertEquals(FieldTerrainType.MOUNTAIN, mountain.getTerrainType());
}
private void checkFinalGameState(Tile[] tiles) {
assertEquals(CityTile.class, tiles[0].getClass());
assertEquals(8, tiles[0].getArmySize());
assertEquals(Optional.of(1), tiles[0].getOwnerPlayerIndex());
assertEquals(CityTile.class, tiles[1].getClass());
assertEquals(2, tiles[1].getArmySize());
assertEquals(Optional.of(1), tiles[1].getOwnerPlayerIndex());
assertEquals(EmptyTile.class, tiles[3].getClass());
assertEquals(12, tiles[3].getArmySize());
assertEquals(Optional.of(1), tiles[3].getOwnerPlayerIndex());
assertEquals(GeneralTile.class, tiles[8].getClass());
assertEquals(3, tiles[8].getArmySize());
assertEquals(Optional.of(1), tiles[8].getOwnerPlayerIndex());
}
private class AttackGeneralBot extends TestBot { | private final Actions actions; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/CityTile.java | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
| import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE; | package pl.joegreen.sergeants.simulator;
class CityTile extends AbstractTile {
CityTile(int tileIndex, int armySize, Optional<Integer> playerIndex) {
super(tileIndex, armySize, playerIndex);
}
CityTile(int tileIndex, int armySize) {
this(tileIndex, armySize, Optional.empty());
}
@Override
public void turn() {
if (hasOwner()) {
armySize++;
}
}
@Override
public TerrainType getTerrainType(boolean visible) { | // Path: src/main/java/pl/joegreen/sergeants/simulator/TerrainType.java
// final static TerrainType TILE_FOG_OBSTACLE = new TerrainType(-4) /* Cities and Mountains show up as Obstacles in the fog of war.*/;
// Path: src/main/java/pl/joegreen/sergeants/simulator/CityTile.java
import java.util.Optional;
import static pl.joegreen.sergeants.simulator.TerrainType.TILE_FOG_OBSTACLE;
package pl.joegreen.sergeants.simulator;
class CityTile extends AbstractTile {
CityTile(int tileIndex, int armySize, Optional<Integer> playerIndex) {
super(tileIndex, armySize, playerIndex);
}
CityTile(int tileIndex, int armySize) {
this(tileIndex, armySize, Optional.empty());
}
@Override
public void turn() {
if (hasOwner()) {
armySize++;
}
}
@Override
public TerrainType getTerrainType(boolean visible) { | return visible ? getOwnerPlayerIndex().map(TerrainType::playerOwnedTerrain).orElse(TerrainType.TILE_EMPTY) : TILE_FOG_OBSTACLE; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */ | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */ | private final GameStartApiResponse startData; |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */
private final GameStartApiResponse startData;
private final int[] rawMapArray;
private final int[] rawCitiesArray;
private final int[] rawGeneralsArray;
/**
* Creates the first game state just after the game is started. Can be done only after both messages are received from server:
* {@link GameStartApiResponse} and {@link GameUpdateApiResponse}. Cannot be use for further updates, as later game updates
* from server contain only differences.
*/ | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */
private final GameStartApiResponse startData;
private final int[] rawMapArray;
private final int[] rawCitiesArray;
private final int[] rawGeneralsArray;
/**
* Creates the first game state just after the game is started. Can be done only after both messages are received from server:
* {@link GameStartApiResponse} and {@link GameUpdateApiResponse}. Cannot be use for further updates, as later game updates
* from server contain only differences.
*/ | public static UpdatableGameState createInitialGameState(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */
private final GameStartApiResponse startData;
private final int[] rawMapArray;
private final int[] rawCitiesArray;
private final int[] rawGeneralsArray;
/**
* Creates the first game state just after the game is started. Can be done only after both messages are received from server:
* {@link GameStartApiResponse} and {@link GameUpdateApiResponse}. Cannot be use for further updates, as later game updates
* from server contain only differences.
*/
public static UpdatableGameState createInitialGameState(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
return new UpdatableGameState( | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
package pl.joegreen.sergeants.framework.model.api;
@ToString
@EqualsAndHashCode
public class UpdatableGameState implements GameState {
/*Actual data returned to clients*/
private final int columns;
private final int rows;
private final ImmutableList<Player> players;
private final ImmutableMap<Position, Field> fieldsMap;
/*caching visibleFieldsMap even though GameState calculates it by default as this map is very likely to be used intensively */
private final ImmutableMap<Position, VisibleField> visibleFieldsMap;
private final int turn;
private final int attackIndex;
/*Data persisted so that it's possible to update the game state */
private final GameStartApiResponse startData;
private final int[] rawMapArray;
private final int[] rawCitiesArray;
private final int[] rawGeneralsArray;
/**
* Creates the first game state just after the game is started. Can be done only after both messages are received from server:
* {@link GameStartApiResponse} and {@link GameUpdateApiResponse}. Cannot be use for further updates, as later game updates
* from server contain only differences.
*/
public static UpdatableGameState createInitialGameState(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
return new UpdatableGameState( | firstUpdateData.getTurn(), startData, MapPatcher.patch(firstUpdateData.getMapDiff(), new int[]{}), |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
| import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | }
@Override
public int getAttackIndex() {
return attackIndex;
}
@Override
public ImmutableMap<Position, Field> getFieldsMap() {
return fieldsMap;
}
@Override
public ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
return visibleFieldsMap;
}
@Override
public ImmutableList<Player> getPlayers() {
return players;
}
@Override
public GameStarted getGameStartedData() {
return new GameStartedApiResponseImpl(startData);
}
private static ImmutableList<Player> createPlayersInfo(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
int numberOfPlayers = startData.getUsernames().length; | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/GameUpdateApiResponse.java
// @Value
// public class GameUpdateApiResponse {
// private int turn;
// /**
// * Diff to update the array with map (tiles/armies) representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("map_diff")
// private int[] mapDiff;
// /**
// * Diff to update the array with cities representation. Use {@link MapPatcher} to apply the diff.
// */
// @JsonProperty("cities_diff")
// private int[] citiesDiff;
// /**
// * Array of indexes of generals, indexed with player index. If general of player is not visible/does not exist, contains -1 in appropriate position.
// */
// private int[] generals;
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// private int attackIndex;
// /**
// * Array indexed by player index, includes things shown in the score table (titles, army, is dead). Does not include stars.
// */
// private ScoreApiResponse[] scores;
// private double[] stars;
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/response/ScoreApiResponse.java
// @Value
// public class ScoreApiResponse {
// /**
// * Number of map tiles owned.
// */
// private int tiles;
// /**
// * Total army size.
// */
// private int total;
// /**
// * Player index.
// */
// @JsonProperty("i")
// private int index;
// /**
// * True if player already lost.
// */
// private boolean dead;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.api.response.GameUpdateApiResponse;
import pl.joegreen.sergeants.api.response.ScoreApiResponse;
import pl.joegreen.sergeants.api.util.MapPatcher;
import pl.joegreen.sergeants.framework.model.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
}
@Override
public int getAttackIndex() {
return attackIndex;
}
@Override
public ImmutableMap<Position, Field> getFieldsMap() {
return fieldsMap;
}
@Override
public ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
return visibleFieldsMap;
}
@Override
public ImmutableList<Player> getPlayers() {
return players;
}
@Override
public GameStarted getGameStartedData() {
return new GameStartedApiResponseImpl(startData);
}
private static ImmutableList<Player> createPlayersInfo(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
int numberOfPlayers = startData.getUsernames().length; | Map<Integer, ScoreApiResponse> scoresMap = createScoresMap(firstUpdateData); |
greenjoe/sergeants | src/test/java/pl/joegreen/sergeants/TestUtils.java | // Path: src/main/java/pl/joegreen/sergeants/api/test/FakeSocket.java
// public class FakeSocket implements Socket{
//
// public final List<Event> receivedEvents = new CopyOnWriteArrayList<>();
// public final Map<String, Consumer<Object[]>> registeredListeners = new ConcurrentHashMap<>();
// boolean connected = false;
//
// public List<Event> getReceivedEventsByName(String name) {
// return receivedEvents.stream().filter(event -> event.name.equals(name)).collect(Collectors.toList());
// }
//
// public void injectEvent(Event event){
// getListener(event.getName()).accept(event.getArguments());
// }
//
// @Override
// public boolean connected() {
// return connected;
// }
//
// @Override
// public void once(String event, Consumer<Object[]> socketListener) {
// registeredListeners.put(event, args -> {
// socketListener.accept(args);
// registeredListeners.remove(event);
// });
// }
//
// @Override
// public void on(String event, Consumer<Object[]> socketListener) {
// registeredListeners.put(event, socketListener);
// }
//
// @Override
// public void connect() {
// connected = true;
// getListener("connect").accept(new Object[]{});
// }
//
// @Override
// public void disconnect() {
// connected = false;
// getListener("disconnect").accept(new Object[]{});
// }
//
//
// private Consumer<Object[]> getListener(String connect) {
// return registeredListeners.getOrDefault(connect, (args) -> {});
// }
//
//
// @Override
// public void emit(String name, Object[] args) {
// receivedEvents.add(new Event(name, args));
// }
//
//
// @Value
// public static class Event{
// private String name;
// private Object[] arguments;
//
// public Event(String name, Object... arguments ){
// this.name = name;
// this.arguments = arguments;
// }
// }
//
//
//
// }
| import pl.joegreen.sergeants.api.test.FakeSocket;
import org.json.JSONException;
import org.json.JSONTokener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList; | package pl.joegreen.sergeants;
public class TestUtils {
/**
* SocketIO java client is using json.org json objects
*/
public static Object asJsonOrgObject(String eventJson) {
try {
return new JSONTokener(eventJson).nextValue();
} catch (JSONException e) {
throw new RuntimeException("Cannot deserialize:" + eventJson, e);
}
}
| // Path: src/main/java/pl/joegreen/sergeants/api/test/FakeSocket.java
// public class FakeSocket implements Socket{
//
// public final List<Event> receivedEvents = new CopyOnWriteArrayList<>();
// public final Map<String, Consumer<Object[]>> registeredListeners = new ConcurrentHashMap<>();
// boolean connected = false;
//
// public List<Event> getReceivedEventsByName(String name) {
// return receivedEvents.stream().filter(event -> event.name.equals(name)).collect(Collectors.toList());
// }
//
// public void injectEvent(Event event){
// getListener(event.getName()).accept(event.getArguments());
// }
//
// @Override
// public boolean connected() {
// return connected;
// }
//
// @Override
// public void once(String event, Consumer<Object[]> socketListener) {
// registeredListeners.put(event, args -> {
// socketListener.accept(args);
// registeredListeners.remove(event);
// });
// }
//
// @Override
// public void on(String event, Consumer<Object[]> socketListener) {
// registeredListeners.put(event, socketListener);
// }
//
// @Override
// public void connect() {
// connected = true;
// getListener("connect").accept(new Object[]{});
// }
//
// @Override
// public void disconnect() {
// connected = false;
// getListener("disconnect").accept(new Object[]{});
// }
//
//
// private Consumer<Object[]> getListener(String connect) {
// return registeredListeners.getOrDefault(connect, (args) -> {});
// }
//
//
// @Override
// public void emit(String name, Object[] args) {
// receivedEvents.add(new Event(name, args));
// }
//
//
// @Value
// public static class Event{
// private String name;
// private Object[] arguments;
//
// public Event(String name, Object... arguments ){
// this.name = name;
// this.arguments = arguments;
// }
// }
//
//
//
// }
// Path: src/test/java/pl/joegreen/sergeants/TestUtils.java
import pl.joegreen.sergeants.api.test.FakeSocket;
import org.json.JSONException;
import org.json.JSONTokener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
package pl.joegreen.sergeants;
public class TestUtils {
/**
* SocketIO java client is using json.org json objects
*/
public static Object asJsonOrgObject(String eventJson) {
try {
return new JSONTokener(eventJson).nextValue();
} catch (JSONException e) {
throw new RuntimeException("Cannot deserialize:" + eventJson, e);
}
}
| public static List<FakeSocket.Event> readEventsFromClassPathFile(String fileName) throws URISyntaxException, IOException { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/ChatMessageApiResponse.java
// @Value
// public class ChatMessageApiResponse {
// /**
// * Name of the author of the message.
// */
// private String username;
// /**
// * Player index of the author of the message.
// */
// private int playerIndex;
// /**
// * Actual content of the message
// */
// private String text;
// }
| import pl.joegreen.sergeants.api.response.ChatMessageApiResponse; | package pl.joegreen.sergeants.api.listener;
@FunctionalInterface
public interface ChatMessageListener { | // Path: src/main/java/pl/joegreen/sergeants/api/response/ChatMessageApiResponse.java
// @Value
// public class ChatMessageApiResponse {
// /**
// * Name of the author of the message.
// */
// private String username;
// /**
// * Player index of the author of the message.
// */
// private int playerIndex;
// /**
// * Actual content of the message
// */
// private String text;
// }
// Path: src/main/java/pl/joegreen/sergeants/api/listener/ChatMessageListener.java
import pl.joegreen.sergeants.api.response.ChatMessageApiResponse;
package pl.joegreen.sergeants.api.listener;
@FunctionalInterface
public interface ChatMessageListener { | void onEvent(String chatRoom, ChatMessageApiResponse message); |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/simulator/viewer/NopViewerWriter.java | // Path: src/main/java/pl/joegreen/sergeants/simulator/GameMap.java
// public class GameMap {
//
// private final Tile[] tiles;
// private int halfTurnCounter = 0;
// private final int width;
// private final int height;
//
// GameMap(Tile[] tiles, int height, int width) {
// if ((height * width) != tiles.length) {
// throw new IllegalArgumentException("Incorrect height and width");
// }
// this.height = height;
// this.width = width;
// this.tiles = tiles;
// }
//
// Tile[] getTiles() {
// return tiles;
// }
//
// void tick() {
// halfTurnCounter++;
//
// if ((halfTurnCounter % 2) == 0) {
// Arrays.stream(tiles).forEach(Tile::turn);
// }
// if ((halfTurnCounter % 50) == 0) {
// Arrays.stream(tiles).forEach(Tile::round);
// }
// }
//
// /**
// * Polls move recursively until it finds a valid move.
// */
// Optional<PlayerKilled> move(Player player) {
// Move move = player.getMoves().poll();
// if (move != null) {
// Tile from = tiles[move.getFrom()];
// boolean armyBigEnough = from.getArmySize() > 1;
// boolean tileAndPlayerMatching = from.isOwnedBy(player.getPlayerIndex());
// boolean oneStepAway = Stream.of(getTileAbove(from), getTileBelow(from), getTileLeftOf(from), getTileRightOf(from))
// .filter(Optional::isPresent).map(Optional::get)
// .map(Tile::getTileIndex)
// .anyMatch(neighbourIndex -> neighbourIndex == move.getTo());
// if (armyBigEnough && tileAndPlayerMatching && oneStepAway) {
// int armySize = from.moveFrom(move.half());
// return tiles[move.getTo()]
// .moveTo(armySize, from.getOwnerPlayerIndex().get(), tiles)
// .map(this::transfer);
// } else {
// return move(player);
// }
// }
// return Optional.empty();
// }
//
// private PlayerKilled transfer(PlayerKilled playerKilled) {
// Arrays.stream(tiles)
// .filter(tile -> tile.isOwnedBy(playerKilled.getVictim()))
// .forEach(tile -> tile.transfer(playerKilled.getOffender()));
// return playerKilled;
// }
//
//
//
// /**
// * Returns all generals, visible and fogged. This is not a problem since bot will still receive tile as fogged (-3).
// *
// * @return list of tileIndex where general is, array index is player index
// */
// int[] getGenerals() {
// return Arrays.stream(tiles)
// .filter(tile1 -> tile1.getClass().equals(GeneralTile.class))
// .sorted(Comparator.comparingInt(t -> t.getOwnerPlayerIndex().get()))
// .mapToInt(Tile::getTileIndex)
// .toArray();
// }
//
// public boolean isVisible(int playerIndex, Tile tile) {
// return tile.isOwnedBy(playerIndex) || getSurroundingTiles(tile).stream().anyMatch(t -> t.isOwnedBy(playerIndex));
// }
//
// private List<Tile> getSurroundingTiles(Tile tile) {
// //this could be prettier
// List<Tile> ret = new ArrayList<>();
// getTileLeftOf(tile).ifPresent(leftTile -> {
// ret.add(leftTile);
// getTileAbove(leftTile).ifPresent(ret::add);
// getTileBelow(leftTile).ifPresent(ret::add);
// });
// getTileRightOf(tile).ifPresent(t -> {
// ret.add(t);
// getTileAbove(t).ifPresent(ret::add);
// getTileBelow(t).ifPresent(ret::add);
// });
// getTileAbove(tile).ifPresent(ret::add);
// getTileBelow(tile).ifPresent(ret::add);
// return ret;
// }
//
// private Optional<Tile> getTileAbove(Tile tile) {
// int tileIndex = tile.getTileIndex() - width;
// return tileIndex >= 0 ? Optional.of(tiles[tileIndex]) : Optional.empty();
// }
//
// private Optional<Tile> getTileBelow(Tile tile) {
// int tileIndex = tile.getTileIndex() + width;
// return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
// }
//
// private Optional<Tile> getTileRightOf(Tile tile) {
// boolean isMostRight = tile.getTileIndex() % width == width - 1;
// return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
// }
//
// private Optional<Tile> getTileLeftOf(Tile tile) {
// int tileIndex = tile.getTileIndex();
// boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
// return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
// }
//
// int getHalfTurnCounter() {
// return halfTurnCounter;
// }
//
// int getHeight() {
// return height;
// }
//
// int getWidth() {
// return width;
// }
//
//
// public static ViewerMapState toViewerMapState(GameMap map) {
// Set<ViewerField> viewerFields = Arrays.stream(map.getTiles()).map(
// tile -> new ViewerField(Position.fromIndex(tile.getTileIndex(), map.getWidth()),
// tile.getOwnerPlayerIndex().orElse(null),
// tile.getArmySize(),
// tile instanceof CityTile,
// tile instanceof GeneralTile,
// tile instanceof MountainTile)
// ).collect(Collectors.toSet());
// return new ViewerMapState(map.getHalfTurnCounter(), map.getHeight(), map.getWidth(), viewerFields);
// }
// }
| import pl.joegreen.sergeants.simulator.GameMap; | package pl.joegreen.sergeants.simulator.viewer;
public class NopViewerWriter implements ViewerWriter {
@Override | // Path: src/main/java/pl/joegreen/sergeants/simulator/GameMap.java
// public class GameMap {
//
// private final Tile[] tiles;
// private int halfTurnCounter = 0;
// private final int width;
// private final int height;
//
// GameMap(Tile[] tiles, int height, int width) {
// if ((height * width) != tiles.length) {
// throw new IllegalArgumentException("Incorrect height and width");
// }
// this.height = height;
// this.width = width;
// this.tiles = tiles;
// }
//
// Tile[] getTiles() {
// return tiles;
// }
//
// void tick() {
// halfTurnCounter++;
//
// if ((halfTurnCounter % 2) == 0) {
// Arrays.stream(tiles).forEach(Tile::turn);
// }
// if ((halfTurnCounter % 50) == 0) {
// Arrays.stream(tiles).forEach(Tile::round);
// }
// }
//
// /**
// * Polls move recursively until it finds a valid move.
// */
// Optional<PlayerKilled> move(Player player) {
// Move move = player.getMoves().poll();
// if (move != null) {
// Tile from = tiles[move.getFrom()];
// boolean armyBigEnough = from.getArmySize() > 1;
// boolean tileAndPlayerMatching = from.isOwnedBy(player.getPlayerIndex());
// boolean oneStepAway = Stream.of(getTileAbove(from), getTileBelow(from), getTileLeftOf(from), getTileRightOf(from))
// .filter(Optional::isPresent).map(Optional::get)
// .map(Tile::getTileIndex)
// .anyMatch(neighbourIndex -> neighbourIndex == move.getTo());
// if (armyBigEnough && tileAndPlayerMatching && oneStepAway) {
// int armySize = from.moveFrom(move.half());
// return tiles[move.getTo()]
// .moveTo(armySize, from.getOwnerPlayerIndex().get(), tiles)
// .map(this::transfer);
// } else {
// return move(player);
// }
// }
// return Optional.empty();
// }
//
// private PlayerKilled transfer(PlayerKilled playerKilled) {
// Arrays.stream(tiles)
// .filter(tile -> tile.isOwnedBy(playerKilled.getVictim()))
// .forEach(tile -> tile.transfer(playerKilled.getOffender()));
// return playerKilled;
// }
//
//
//
// /**
// * Returns all generals, visible and fogged. This is not a problem since bot will still receive tile as fogged (-3).
// *
// * @return list of tileIndex where general is, array index is player index
// */
// int[] getGenerals() {
// return Arrays.stream(tiles)
// .filter(tile1 -> tile1.getClass().equals(GeneralTile.class))
// .sorted(Comparator.comparingInt(t -> t.getOwnerPlayerIndex().get()))
// .mapToInt(Tile::getTileIndex)
// .toArray();
// }
//
// public boolean isVisible(int playerIndex, Tile tile) {
// return tile.isOwnedBy(playerIndex) || getSurroundingTiles(tile).stream().anyMatch(t -> t.isOwnedBy(playerIndex));
// }
//
// private List<Tile> getSurroundingTiles(Tile tile) {
// //this could be prettier
// List<Tile> ret = new ArrayList<>();
// getTileLeftOf(tile).ifPresent(leftTile -> {
// ret.add(leftTile);
// getTileAbove(leftTile).ifPresent(ret::add);
// getTileBelow(leftTile).ifPresent(ret::add);
// });
// getTileRightOf(tile).ifPresent(t -> {
// ret.add(t);
// getTileAbove(t).ifPresent(ret::add);
// getTileBelow(t).ifPresent(ret::add);
// });
// getTileAbove(tile).ifPresent(ret::add);
// getTileBelow(tile).ifPresent(ret::add);
// return ret;
// }
//
// private Optional<Tile> getTileAbove(Tile tile) {
// int tileIndex = tile.getTileIndex() - width;
// return tileIndex >= 0 ? Optional.of(tiles[tileIndex]) : Optional.empty();
// }
//
// private Optional<Tile> getTileBelow(Tile tile) {
// int tileIndex = tile.getTileIndex() + width;
// return tileIndex < tiles.length ? Optional.of(tiles[tileIndex]) : Optional.empty();
// }
//
// private Optional<Tile> getTileRightOf(Tile tile) {
// boolean isMostRight = tile.getTileIndex() % width == width - 1;
// return isMostRight ? Optional.empty() : Optional.of(tiles[tile.getTileIndex() + 1]);
// }
//
// private Optional<Tile> getTileLeftOf(Tile tile) {
// int tileIndex = tile.getTileIndex();
// boolean isMostLeft = tileIndex == 0 || tileIndex % width == 0;
// return isMostLeft ? Optional.empty() : Optional.of(tiles[tileIndex - 1]);
// }
//
// int getHalfTurnCounter() {
// return halfTurnCounter;
// }
//
// int getHeight() {
// return height;
// }
//
// int getWidth() {
// return width;
// }
//
//
// public static ViewerMapState toViewerMapState(GameMap map) {
// Set<ViewerField> viewerFields = Arrays.stream(map.getTiles()).map(
// tile -> new ViewerField(Position.fromIndex(tile.getTileIndex(), map.getWidth()),
// tile.getOwnerPlayerIndex().orElse(null),
// tile.getArmySize(),
// tile instanceof CityTile,
// tile instanceof GeneralTile,
// tile instanceof MountainTile)
// ).collect(Collectors.toSet());
// return new ViewerMapState(map.getHalfTurnCounter(), map.getHeight(), map.getWidth(), viewerFields);
// }
// }
// Path: src/main/java/pl/joegreen/sergeants/simulator/viewer/NopViewerWriter.java
import pl.joegreen.sergeants.simulator.GameMap;
package pl.joegreen.sergeants.simulator.viewer;
public class NopViewerWriter implements ViewerWriter {
@Override | public void write(GameMap gameMap) {} |
greenjoe/sergeants | src/test/java/pl/joegreen/sergeants/simulator/DoNothingBot.java | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
| import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.GameState; | package pl.joegreen.sergeants.simulator;
class DoNothingBot extends TestBot {
private final Actions actions;
public DoNothingBot(Actions actions) {
this.actions = actions;
}
@Override | // Path: src/main/java/pl/joegreen/sergeants/framework/Actions.java
// public interface Actions {
//
// void move(int indexFrom, int indexTo);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// */
// void move(Field fieldFrom, Field fieldTo);
//
// void move(int indexFrom, int indexTo, boolean moveHalf);
//
// /**
// * Direct move between fields. Works only if both fields are neighbours (either horizontally or vertically, not diagonally) - otherwise does nothing and logs error.
// * @param moveHalf if true, only half of the army will be moved (equal to double click in browser)
// */
// void move(Field fieldFrom, Field fieldTo, boolean moveHalf);
//
// void sendChat(String message);
//
// void sendTeamChat(String message);
//
// void leaveGame();
//
// void ping(int index);
//
// void ping(Field field);
//
// /**
// * Remove all moves from the move queue.
// */
// void clearMoves();
//
// /**
// * Get lower level API that potentially can make it possible to do something that is not possible by this interface.
// * Use with caution, as using it can potentially make the framework work unexpectedly.
// */
// GeneralsApi getBareApi();
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameState.java
// public interface GameState extends GameStateFieldContext {
// /**
// * Horizontal size of the map. Does not change during the game.
// */
// int getColumns();
//
// /**
// * Vertical size of the map. Does not change during the game.
// */
// int getRows();
//
// /**
// * "Server turn" which is increased after every update (possibility of making a move). Is not the same as turn number
// * displayed in browser (browser turn is equal to two server turns).
// */
// int getTurn();
//
// /**
// * Officially "the attackIndex field is unnecessary for bots -- it's used by our client to show/hide attack arrows when appropriate."
// * Some people say it can be used to find out state of moves queue and plan more complex moves ;-)
// */
// int getAttackIndex();
//
// /**
// * Players currently playing and those already dead. Represents the table that is displayed in browser in the
// * top right corner of the map.
// */
// ImmutableList<Player> getPlayers();
//
// ImmutableMap<Position, Field> getFieldsMap();
//
// GameStarted getGameStartedData();
//
// default Player getMyPlayer() {
// return getPlayers().get(getMyPlayerIndex());
// }
//
// default ImmutableMap<Position, VisibleField> getVisibleFieldsMap() {
// return ImmutableMap.copyOf(getFieldsMap().values().stream()
// .filter(Field::isVisible)
// .map(Field::asVisibleField)
// .collect(Collectors.toMap(Field::getPosition, Functions.identity())));
// }
//
// default Collection<Field> getFields() {
// return getFieldsMap().values();
// }
//
// default Collection<VisibleField> getVisibleFields() {
// return getVisibleFieldsMap().values();
// }
//
// default Field[][] getTwoDimensionalArrayOfFields() {
// Field[][] array = new Field[getRows()][getColumns()];
// for (int row = 0; row < getRows(); ++row) {
// for (int col = 0; col < getColumns(); ++col) {
// array[row][col] = getFieldsMap().get(new Position(row, col));
// }
// }
// return array;
// }
//
// default Position positionFromIndex(int index) {
// return Position.fromIndex(index, getColumns());
// }
//
// default int positionToIndex(Position position) {
// return position.toIndex(getColumns());
// }
//
// default boolean isValidPosition(Position position) {
// return position.getCol() < getColumns() && position.getCol() >= 0 && position.getRow() >= 0 && position.getRow() < getRows();
// }
//
// default Set<Integer> getMyTeamIndexes() {
// return getPlayers().stream().filter(
// player -> player.getTeam().equals(getPlayers().get(getMyPlayerIndex()).getTeam()))
// .mapToInt(Player::getIndex)
// .boxed()
// .collect(Collectors.toSet());
// }
//
//
// /**
// * Index of bot's player.
// */
// default int getMyPlayerIndex() {
// return getGameStartedData().getPlayerIndex();
// }
//
// /**
// * Replay identifier. Replays are available only after game is finished.
// * Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// default String getReplayId() {
// return getGameStartedData().getReplayId();
// }
//
// /**
// * Identifier of the main game chat room.
// */
// default String getChatRoom() {
// return getGameStartedData().getChatRoom();
// }
//
// /**
// * Identifier of the private team chat room.
// */
// default String getTeamChatRoom() {
// return getGameStartedData().getTeamChatRoom();
// }
//
// default Set<Position> getNeighbourPositions(Position position) {
// return Stream.of(
// position.withCol(position.getCol() + 1),
// position.withCol(position.getCol() - 1),
// position.withRow(position.getRow() + 1),
// position.withRow(position.getRow() - 1)
// ).filter(this::isValidPosition).collect(Collectors.toSet());
// }
//
// default Set<Field> getNeighbours(Field field) {
// return getNeighbourPositions(field.getPosition())
// .stream()
// .map(this.getFieldsMap()::get)
// .collect(Collectors.toSet());
// }
//
//
//
// }
// Path: src/test/java/pl/joegreen/sergeants/simulator/DoNothingBot.java
import pl.joegreen.sergeants.framework.Actions;
import pl.joegreen.sergeants.framework.model.GameState;
package pl.joegreen.sergeants.simulator;
class DoNothingBot extends TestBot {
private final Actions actions;
public DoNothingBot(Actions actions) {
this.actions = actions;
}
@Override | public void onGameStateUpdate(GameState newGameState) { |
greenjoe/sergeants | src/test/java/pl/joegreen/sergeants/MapPatcherTest.java | // Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.api.util.MapPatcher; | package pl.joegreen.sergeants;
public class MapPatcherTest {
@Test
public void testExample1(){
int[] old = new int[]{0,0};
int[] patch = new int[]{1,1,3};
int[] expectedNew = new int[]{0,3}; | // Path: src/main/java/pl/joegreen/sergeants/api/util/MapPatcher.java
// public class MapPatcher {
//
// public static int[] patch(int[] patch, int[] old) {
// ArrayList<Integer> newArrayList = new ArrayList<>();
// int patchIndex = 0;
// while (patchIndex < patch.length) {
// //matching
// int matchingElements = patch[patchIndex++];
// int startingIndex = newArrayList.size();
// for (int oldIndex = startingIndex; oldIndex < startingIndex + matchingElements; ++oldIndex) {
// if (oldIndex < old.length) {
// newArrayList.add(old[oldIndex]);
// } else {
// newArrayList.add(0);
// }
// }
//
// //mismatching
// if (patchIndex < patch.length) {
// int misMatchingElements = patch[patchIndex++];
// while (misMatchingElements > 0) {
// newArrayList.add(patch[patchIndex++]);
// misMatchingElements--;
// }
// }
// }
// return newArrayList.stream().mapToInt(i -> i).toArray();
// }
// }
// Path: src/test/java/pl/joegreen/sergeants/MapPatcherTest.java
import org.junit.Assert;
import org.junit.Test;
import pl.joegreen.sergeants.api.util.MapPatcher;
package pl.joegreen.sergeants;
public class MapPatcherTest {
@Test
public void testExample1(){
int[] old = new int[]{0,0};
int[] patch = new int[]{1,1,3};
int[] expectedNew = new int[]{0,3}; | Assert.assertArrayEquals(expectedNew, MapPatcher.patch(patch, old)); |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/GameStartedApiResponseImpl.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameStarted.java
// public interface GameStarted {
// /**
// * See {@link UpdatableGameState#getReplayId()}
// */
// String getReplayId();
//
// String[] getUsernames();
//
// int getPlayerIndex();
//
// String getChatRoom();
//
// String getTeamChatRoom();
// }
| import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.framework.model.GameStarted; | package pl.joegreen.sergeants.framework.model.api;
@EqualsAndHashCode
@ToString | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameStarted.java
// public interface GameStarted {
// /**
// * See {@link UpdatableGameState#getReplayId()}
// */
// String getReplayId();
//
// String[] getUsernames();
//
// int getPlayerIndex();
//
// String getChatRoom();
//
// String getTeamChatRoom();
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/GameStartedApiResponseImpl.java
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.framework.model.GameStarted;
package pl.joegreen.sergeants.framework.model.api;
@EqualsAndHashCode
@ToString | public class GameStartedApiResponseImpl implements GameStarted { |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/GameStartedApiResponseImpl.java | // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameStarted.java
// public interface GameStarted {
// /**
// * See {@link UpdatableGameState#getReplayId()}
// */
// String getReplayId();
//
// String[] getUsernames();
//
// int getPlayerIndex();
//
// String getChatRoom();
//
// String getTeamChatRoom();
// }
| import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.framework.model.GameStarted; | package pl.joegreen.sergeants.framework.model.api;
@EqualsAndHashCode
@ToString
public class GameStartedApiResponseImpl implements GameStarted {
| // Path: src/main/java/pl/joegreen/sergeants/api/response/GameStartApiResponse.java
// @Value
// public class GameStartApiResponse {
// /**
// * Index of bot's player.
// */
// private int playerIndex;
// /**
// * Replay identifier. Use http://bot.generals.io/replays/{replayId} to see the replay in your browser.
// */
// @JsonProperty("replay_id")
// private String replayId;
// /**
// * Identifier of the main chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// */
// @JsonProperty("chat_room")
// private String chatRoom;
// /**
// * Identifier of the team chat room, useful when sending a chat message ({@link GeneralsApi#sendChatMessage(String, String)}).
// * Can be null if there are no teams in the game.
// */
// @JsonProperty("team_chat_room")
// private String teamChatRoom;
// /**
// * Array of player names, indexed by player index.
// */
// private String[] usernames;
// /**
// * Array if team identifiers of each player, indexed by player index. Can be null if there are no teams/
// */
// private Integer[] teams;
//
// }
//
// Path: src/main/java/pl/joegreen/sergeants/framework/model/GameStarted.java
// public interface GameStarted {
// /**
// * See {@link UpdatableGameState#getReplayId()}
// */
// String getReplayId();
//
// String[] getUsernames();
//
// int getPlayerIndex();
//
// String getChatRoom();
//
// String getTeamChatRoom();
// }
// Path: src/main/java/pl/joegreen/sergeants/framework/model/api/GameStartedApiResponseImpl.java
import lombok.EqualsAndHashCode;
import lombok.ToString;
import pl.joegreen.sergeants.api.response.GameStartApiResponse;
import pl.joegreen.sergeants.framework.model.GameStarted;
package pl.joegreen.sergeants.framework.model.api;
@EqualsAndHashCode
@ToString
public class GameStartedApiResponseImpl implements GameStarted {
| private final GameStartApiResponse gameStartApiResponse; |
asmehra95/wiseowl | src/main/java/com/wiseowl/WiseOwl/query/Passage.java | // Path: src/main/java/com/wiseowl/WiseOwl/query/WindowTerm.java
// public class WindowTerm implements Cloneable, Comparable<WindowTerm> {
// String term;
// int position;
// int start, end = -1;
//
// WindowTerm(String term, int position, int startOffset, int endOffset) {
// this.term = term;
// this.position = position;
// this.start = startOffset;
// this.end = endOffset;
// }
//
// public WindowTerm(String s, int position) {
// this.term = s;
// this.position = position;
// }
//
// @Override
// public Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
//
// public int compareTo(WindowTerm other) {
// int result = position - other.position;
// if (result == 0) {
// result = term.compareTo(other.term);
// }
// return result;
// }
//
// @Override
// public String toString() {
// return "WindowEntry{" +
// "term='" + term + '\'' +
// ", position=" + position +
// '}';
// }
// }
| import com.wiseowl.WiseOwl.query.WindowTerm;
import java.util.SortedSet;
import java.util.TreeSet; | /* Copyright 2008-2011 Grant Ingersoll, Thomas Morton and Drew Farris
*
* 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.
* -------------------
* To purchase or learn more about Taming Text, by Grant Ingersoll, Thomas Morton and Drew Farris, visit
* http://www.manning.com/ingersoll
* This code has been modified and upgraded by WiseOwl Team, Avtar Singh, Sumit Kumar and Yuvraj Singh.
* Modifications are copyright 2016-2017 WiseOwl Team, Avtar Singh, Sumit Kumar and Yuvraj Singh
* https://www.linkedin.com/in/avtar-singh-6a481a124/
*/
package com.wiseowl.WiseOwl.query;
class Passage implements Cloneable {
int lDocId;
String field;
float score; | // Path: src/main/java/com/wiseowl/WiseOwl/query/WindowTerm.java
// public class WindowTerm implements Cloneable, Comparable<WindowTerm> {
// String term;
// int position;
// int start, end = -1;
//
// WindowTerm(String term, int position, int startOffset, int endOffset) {
// this.term = term;
// this.position = position;
// this.start = startOffset;
// this.end = endOffset;
// }
//
// public WindowTerm(String s, int position) {
// this.term = s;
// this.position = position;
// }
//
// @Override
// public Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
//
// public int compareTo(WindowTerm other) {
// int result = position - other.position;
// if (result == 0) {
// result = term.compareTo(other.term);
// }
// return result;
// }
//
// @Override
// public String toString() {
// return "WindowEntry{" +
// "term='" + term + '\'' +
// ", position=" + position +
// '}';
// }
// }
// Path: src/main/java/com/wiseowl/WiseOwl/query/Passage.java
import com.wiseowl.WiseOwl.query.WindowTerm;
import java.util.SortedSet;
import java.util.TreeSet;
/* Copyright 2008-2011 Grant Ingersoll, Thomas Morton and Drew Farris
*
* 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.
* -------------------
* To purchase or learn more about Taming Text, by Grant Ingersoll, Thomas Morton and Drew Farris, visit
* http://www.manning.com/ingersoll
* This code has been modified and upgraded by WiseOwl Team, Avtar Singh, Sumit Kumar and Yuvraj Singh.
* Modifications are copyright 2016-2017 WiseOwl Team, Avtar Singh, Sumit Kumar and Yuvraj Singh
* https://www.linkedin.com/in/avtar-singh-6a481a124/
*/
package com.wiseowl.WiseOwl.query;
class Passage implements Cloneable {
int lDocId;
String field;
float score; | SortedSet<WindowTerm> terms = new TreeSet<WindowTerm>(); |
asmehra95/wiseowl | src/main/java/com/wiseowl/WiseOwl/wikiClean/WikiCleanBuilder.java | // Path: src/main/java/com/wiseowl/WiseOwl/wikiClean/WikiClean.java
// public enum WikiLanguage {
// EN, DE, ZH
// };
| import com.wiseowl.WiseOwl.wikiClean.WikiClean.WikiLanguage; | /**
* WikiClean: A Java Wikipedia markup to plain text converter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wiseowl.WiseOwl.wikiClean;
public class WikiCleanBuilder {
private boolean withTitle = false;
private boolean withFooter = false; | // Path: src/main/java/com/wiseowl/WiseOwl/wikiClean/WikiClean.java
// public enum WikiLanguage {
// EN, DE, ZH
// };
// Path: src/main/java/com/wiseowl/WiseOwl/wikiClean/WikiCleanBuilder.java
import com.wiseowl.WiseOwl.wikiClean.WikiClean.WikiLanguage;
/**
* WikiClean: A Java Wikipedia markup to plain text converter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wiseowl.WiseOwl.wikiClean;
public class WikiCleanBuilder {
private boolean withTitle = false;
private boolean withFooter = false; | private WikiLanguage lang = WikiLanguage.EN; |
mapsforge/mapsforge | mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/ContentRenderTheme.java | // Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlThemeResourceProvider.java
// public interface XmlThemeResourceProvider {
//
// /**
// * @param relativePath a relative path to use as a base for search in the resource provuider
// * @param source a source string parsed out of an XML render theme "src" attribute.
// * @return an InputStream to read the resource data from.
// * @throws IOException if the resource cannot be found or an access error occurred.
// */
// InputStream createInputStream(String relativePath, String source) throws IOException;
// }
| import android.content.ContentResolver;
import android.net.Uri;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlThemeResourceProvider;
import java.io.IOException;
import java.io.InputStream; | /*
* Copyright 2020-2021 devemux86
* Copyright 2021 eddiemuc
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.android.rendertheme;
/**
* An ContentRenderTheme allows for customizing the rendering style of the map
* via an XML from the Android content providers.
*/
public class ContentRenderTheme implements XmlRenderTheme {
private final ContentResolver contentResolver;
private XmlRenderThemeMenuCallback menuCallback; | // Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlThemeResourceProvider.java
// public interface XmlThemeResourceProvider {
//
// /**
// * @param relativePath a relative path to use as a base for search in the resource provuider
// * @param source a source string parsed out of an XML render theme "src" attribute.
// * @return an InputStream to read the resource data from.
// * @throws IOException if the resource cannot be found or an access error occurred.
// */
// InputStream createInputStream(String relativePath, String source) throws IOException;
// }
// Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/ContentRenderTheme.java
import android.content.ContentResolver;
import android.net.Uri;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlThemeResourceProvider;
import java.io.IOException;
import java.io.InputStream;
/*
* Copyright 2020-2021 devemux86
* Copyright 2021 eddiemuc
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.android.rendertheme;
/**
* An ContentRenderTheme allows for customizing the rendering style of the map
* via an XML from the Android content providers.
*/
public class ContentRenderTheme implements XmlRenderTheme {
private final ContentResolver contentResolver;
private XmlRenderThemeMenuCallback menuCallback; | private XmlThemeResourceProvider resourceProvider; |
mapsforge/mapsforge | mapsforge-core/src/main/java/org/mapsforge/core/model/LatLong.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
| import org.mapsforge.core.util.LatLongUtils;
import org.mapsforge.core.util.Parameters;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2015-2022 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.core.model;
/**
* This immutable class represents a geographic coordinate with a latitude and longitude value.
*/
public class LatLong implements Comparable<LatLong> {
/**
* The RegEx pattern to read WKT points.
*/
private static final Pattern WKT_POINT_PATTERN = Pattern
.compile(".*POINT\\s?\\(([\\d\\.]+)\\s([\\d\\.]+)\\).*");
/**
* The internal latitude value.
*/
public final double latitude;
/**
* The internal longitude value.
*/
public final double longitude;
/**
* Constructs a new LatLong with the given latitude and longitude values, measured in
* degrees.
*
* @param latitude the latitude value in degrees.
* @param longitude the longitude value in degrees.
* @throws IllegalArgumentException if the latitude or longitude value is invalid.
*/
public LatLong(double latitude, double longitude) throws IllegalArgumentException { | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
// Path: mapsforge-core/src/main/java/org/mapsforge/core/model/LatLong.java
import org.mapsforge.core.util.LatLongUtils;
import org.mapsforge.core.util.Parameters;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2015-2022 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.core.model;
/**
* This immutable class represents a geographic coordinate with a latitude and longitude value.
*/
public class LatLong implements Comparable<LatLong> {
/**
* The RegEx pattern to read WKT points.
*/
private static final Pattern WKT_POINT_PATTERN = Pattern
.compile(".*POINT\\s?\\(([\\d\\.]+)\\s([\\d\\.]+)\\).*");
/**
* The internal latitude value.
*/
public final double latitude;
/**
* The internal longitude value.
*/
public final double longitude;
/**
* Constructs a new LatLong with the given latitude and longitude values, measured in
* degrees.
*
* @param latitude the latitude value in degrees.
* @param longitude the longitude value in degrees.
* @throws IllegalArgumentException if the latitude or longitude value is invalid.
*/
public LatLong(double latitude, double longitude) throws IllegalArgumentException { | this.latitude = Parameters.VALIDATE_COORDINATES ? LatLongUtils.validateLatitude(latitude) : latitude; |
mapsforge/mapsforge | mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/ReadBuffer.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
| import org.mapsforge.core.model.Tag;
import org.mapsforge.core.util.Parameters;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2015-2020 devemux86
* Copyright 2016 bvgastel
* Copyright 2017 linuskr
* Copyright 2017 Gustl22
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.reader;
/**
* Reads from a {@link RandomAccessFile} into a buffer and decodes the data.
*/
public class ReadBuffer {
private static final String CHARSET_UTF8 = "UTF-8";
private static final Logger LOGGER = Logger.getLogger(ReadBuffer.class.getName());
private byte[] bufferData;
private int bufferPosition;
private ByteBuffer bufferWrapper;
private final FileChannel inputChannel;
private final List<Integer> tagIds = new ArrayList<>();
ReadBuffer(FileChannel inputChannel) {
this.inputChannel = inputChannel;
}
/**
* Returns one byte from the read buffer.
*
* @return the byte value.
*/
public byte readByte() {
return this.bufferData[this.bufferPosition++];
}
/**
* Converts four bytes from the read buffer to a float.
* <p/>
* The byte order is big-endian.
*
* @return the float value.
*/
public float readFloat() {
return Float.intBitsToFloat(readInt());
}
/**
* Reads the given amount of bytes from the file into the read buffer and resets the internal buffer position. If
* the capacity of the read buffer is too small, a larger one is created automatically.
*
* @param length the amount of bytes to read from the file.
* @return true if the whole data was read successfully, false otherwise.
* @throws IOException if an error occurs while reading the file.
*/
public boolean readFromFile(int length) throws IOException {
// ensure that the read buffer is large enough
if (this.bufferData == null || this.bufferData.length < length) {
// ensure that the read buffer is not too large | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
// Path: mapsforge-map-reader/src/main/java/org/mapsforge/map/reader/ReadBuffer.java
import org.mapsforge.core.model.Tag;
import org.mapsforge.core.util.Parameters;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2015-2020 devemux86
* Copyright 2016 bvgastel
* Copyright 2017 linuskr
* Copyright 2017 Gustl22
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.reader;
/**
* Reads from a {@link RandomAccessFile} into a buffer and decodes the data.
*/
public class ReadBuffer {
private static final String CHARSET_UTF8 = "UTF-8";
private static final Logger LOGGER = Logger.getLogger(ReadBuffer.class.getName());
private byte[] bufferData;
private int bufferPosition;
private ByteBuffer bufferWrapper;
private final FileChannel inputChannel;
private final List<Integer> tagIds = new ArrayList<>();
ReadBuffer(FileChannel inputChannel) {
this.inputChannel = inputChannel;
}
/**
* Returns one byte from the read buffer.
*
* @return the byte value.
*/
public byte readByte() {
return this.bufferData[this.bufferPosition++];
}
/**
* Converts four bytes from the read buffer to a float.
* <p/>
* The byte order is big-endian.
*
* @return the float value.
*/
public float readFloat() {
return Float.intBitsToFloat(readInt());
}
/**
* Reads the given amount of bytes from the file into the read buffer and resets the internal buffer position. If
* the capacity of the read buffer is too small, a larger one is created automatically.
*
* @param length the amount of bytes to read from the file.
* @return true if the whole data was read successfully, false otherwise.
* @throws IOException if an error occurs while reading the file.
*/
public boolean readFromFile(int length) throws IOException {
// ensure that the read buffer is large enough
if (this.bufferData == null || this.bufferData.length < length) {
// ensure that the read buffer is not too large | if (length > Parameters.MAXIMUM_BUFFER_SIZE) { |
mapsforge/mapsforge | mapsforge-map-awt/src/main/java/org/mapsforge/map/awt/graphics/AwtCanvas.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
| import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.util.AbstractMap;
import java.util.Map;
import org.mapsforge.core.graphics.Canvas;
import org.mapsforge.core.graphics.Color;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.graphics.*;
import org.mapsforge.core.model.Dimension;
import org.mapsforge.core.model.Rectangle;
import org.mapsforge.core.util.Parameters;
import java.awt.*;
import java.awt.color.ColorSpace; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014-2021 devemux86
* Copyright 2017 usrusr
* Copyright 2019 cpt1gl0
* Copyright 2019 Adrian Batzill
* Copyright 2019 Matthew Egeler
* Copyright 2019 mg4gh
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.awt.graphics;
class AwtCanvas implements Canvas {
private static final String UNKNOWN_STYLE = "unknown style: ";
private BufferedImage bufferedImage;
private Graphics2D graphics2D;
private BufferedImageOp grayscaleOp, invertOp, invertOp4;
private static final java.awt.Color NEUTRAL_HILLS = new java.awt.Color(127, 127, 127);
private static Map.Entry<Float, Composite> sizeOneShadingCompositeCache = null;
private final AffineTransform transform = new AffineTransform();
private static Composite getHillshadingComposite(float magnitude) {
Map.Entry<Float, Composite> existing = sizeOneShadingCompositeCache;
if (existing != null && existing.getKey() == magnitude) {
// JMM says: "A thread-safe immutable object is seen as immutable by all threads, even
// if a data race is used to pass references to the immutable object between threads"
// worst case we construct more than strictly needed
return existing.getValue();
}
Composite selected = selectHillShadingComposite(magnitude);
if (sizeOneShadingCompositeCache == null) {
// only cache the first magnitude value, in the rare instance that more than one
// magnitude value would be used in a process lifecycle it would be better to create
// new Composite instances than create new instances _and_ new cache entries
sizeOneShadingCompositeCache = new AbstractMap.SimpleImmutableEntry<>(magnitude, selected);
}
return selected;
}
/**
* Composite selection, select between {@link AlphaComposite} (fast, squashes saturation at high magnitude)
* and {@link AwtLuminanceShadingComposite} (per-pixel rgb->hsv->rgb conversion to keep saturation at high magnitude,
* might be a bit slow and/or inconsistent with the android implementation)
*/
private static Composite selectHillShadingComposite(float magnitude) {
//return new AwtLuminanceShadingComposite(magnitude);
return AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, magnitude);
}
AwtCanvas() {
createFilters();
}
AwtCanvas(Graphics2D graphics2D) {
this.graphics2D = graphics2D; | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
// Path: mapsforge-map-awt/src/main/java/org/mapsforge/map/awt/graphics/AwtCanvas.java
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.util.AbstractMap;
import java.util.Map;
import org.mapsforge.core.graphics.Canvas;
import org.mapsforge.core.graphics.Color;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.graphics.*;
import org.mapsforge.core.model.Dimension;
import org.mapsforge.core.model.Rectangle;
import org.mapsforge.core.util.Parameters;
import java.awt.*;
import java.awt.color.ColorSpace;
/*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014-2021 devemux86
* Copyright 2017 usrusr
* Copyright 2019 cpt1gl0
* Copyright 2019 Adrian Batzill
* Copyright 2019 Matthew Egeler
* Copyright 2019 mg4gh
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.awt.graphics;
class AwtCanvas implements Canvas {
private static final String UNKNOWN_STYLE = "unknown style: ";
private BufferedImage bufferedImage;
private Graphics2D graphics2D;
private BufferedImageOp grayscaleOp, invertOp, invertOp4;
private static final java.awt.Color NEUTRAL_HILLS = new java.awt.Color(127, 127, 127);
private static Map.Entry<Float, Composite> sizeOneShadingCompositeCache = null;
private final AffineTransform transform = new AffineTransform();
private static Composite getHillshadingComposite(float magnitude) {
Map.Entry<Float, Composite> existing = sizeOneShadingCompositeCache;
if (existing != null && existing.getKey() == magnitude) {
// JMM says: "A thread-safe immutable object is seen as immutable by all threads, even
// if a data race is used to pass references to the immutable object between threads"
// worst case we construct more than strictly needed
return existing.getValue();
}
Composite selected = selectHillShadingComposite(magnitude);
if (sizeOneShadingCompositeCache == null) {
// only cache the first magnitude value, in the rare instance that more than one
// magnitude value would be used in a process lifecycle it would be better to create
// new Composite instances than create new instances _and_ new cache entries
sizeOneShadingCompositeCache = new AbstractMap.SimpleImmutableEntry<>(magnitude, selected);
}
return selected;
}
/**
* Composite selection, select between {@link AlphaComposite} (fast, squashes saturation at high magnitude)
* and {@link AwtLuminanceShadingComposite} (per-pixel rgb->hsv->rgb conversion to keep saturation at high magnitude,
* might be a bit slow and/or inconsistent with the android implementation)
*/
private static Composite selectHillShadingComposite(float magnitude) {
//return new AwtLuminanceShadingComposite(magnitude);
return AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, magnitude);
}
AwtCanvas() {
createFilters();
}
AwtCanvas(Graphics2D graphics2D) {
this.graphics2D = graphics2D; | setAntiAlias(Parameters.ANTI_ALIASING); |
mapsforge/mapsforge | mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
| import org.mapsforge.core.util.LatLongUtils;
import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.core.util.Parameters;
import java.io.Serializable;
import java.util.List; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014 Christian Pesch
* Copyright 2015-2022 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.core.model;
/**
* A BoundingBox represents an immutable set of two latitude and two longitude coordinates.
*/
public class BoundingBox implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new BoundingBox from a comma-separated string of coordinates in the order minLat, minLon, maxLat,
* maxLon. All coordinate values must be in degrees.
*
* @param boundingBoxString the string that describes the BoundingBox.
* @return a new BoundingBox with the given coordinates.
* @throws IllegalArgumentException if the string cannot be parsed or describes an invalid BoundingBox.
*/
public static BoundingBox fromString(String boundingBoxString) {
double[] coordinates = LatLongUtils.parseCoordinateString(boundingBoxString, 4);
return new BoundingBox(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
}
/**
* The maximum latitude coordinate of this BoundingBox in degrees.
*/
public final double maxLatitude;
/**
* The maximum longitude coordinate of this BoundingBox in degrees.
*/
public final double maxLongitude;
/**
* The minimum latitude coordinate of this BoundingBox in degrees.
*/
public final double minLatitude;
/**
* The minimum longitude coordinate of this BoundingBox in degrees.
*/
public final double minLongitude;
/**
* @param minLatitude the minimum latitude coordinate in degrees.
* @param minLongitude the minimum longitude coordinate in degrees.
* @param maxLatitude the maximum latitude coordinate in degrees.
* @param maxLongitude the maximum longitude coordinate in degrees.
* @throws IllegalArgumentException if a coordinate is invalid.
*/
public BoundingBox(double minLatitude, double minLongitude, double maxLatitude, double maxLongitude) { | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
// Path: mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java
import org.mapsforge.core.util.LatLongUtils;
import org.mapsforge.core.util.MercatorProjection;
import org.mapsforge.core.util.Parameters;
import java.io.Serializable;
import java.util.List;
/*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014 Christian Pesch
* Copyright 2015-2022 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.core.model;
/**
* A BoundingBox represents an immutable set of two latitude and two longitude coordinates.
*/
public class BoundingBox implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new BoundingBox from a comma-separated string of coordinates in the order minLat, minLon, maxLat,
* maxLon. All coordinate values must be in degrees.
*
* @param boundingBoxString the string that describes the BoundingBox.
* @return a new BoundingBox with the given coordinates.
* @throws IllegalArgumentException if the string cannot be parsed or describes an invalid BoundingBox.
*/
public static BoundingBox fromString(String boundingBoxString) {
double[] coordinates = LatLongUtils.parseCoordinateString(boundingBoxString, 4);
return new BoundingBox(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
}
/**
* The maximum latitude coordinate of this BoundingBox in degrees.
*/
public final double maxLatitude;
/**
* The maximum longitude coordinate of this BoundingBox in degrees.
*/
public final double maxLongitude;
/**
* The minimum latitude coordinate of this BoundingBox in degrees.
*/
public final double minLatitude;
/**
* The minimum longitude coordinate of this BoundingBox in degrees.
*/
public final double minLongitude;
/**
* @param minLatitude the minimum latitude coordinate in degrees.
* @param minLongitude the minimum longitude coordinate in degrees.
* @param maxLatitude the maximum latitude coordinate in degrees.
* @param maxLongitude the maximum longitude coordinate in degrees.
* @throws IllegalArgumentException if a coordinate is invalid.
*/
public BoundingBox(double minLatitude, double minLongitude, double maxLatitude, double maxLongitude) { | if (Parameters.VALIDATE_COORDINATES) { |
mapsforge/mapsforge | mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/MarkerBitmap.java | // Path: mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/Utils.java
// public final class Utils {
// /**
// * Compatibility method.
// *
// * @param a the current activity
// */
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void enableHome(Activity a) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// // Show the Up button in the action bar.
// a.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Compatibility method.
// *
// * @param view the view to set the background on
// * @param background the background
// */
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
// @SuppressWarnings("deprecation")
// public static void setBackground(View view, Drawable background) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// view.setBackground(background);
// } else {
// view.setBackgroundDrawable(background);
// }
// }
//
// static Marker createMarker(Context c, int resourceIdentifier,
// LatLong latLong) {
// Bitmap bitmap = new AndroidBitmap(BitmapFactory.decodeResource(c.getResources(), resourceIdentifier));
// return new Marker(latLong, bitmap, 0, -bitmap.getHeight() / 2);
// }
//
// static Paint createPaint(int color, int strokeWidth, Style style) {
// Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
// paint.setColor(color);
// paint.setStrokeWidth(strokeWidth);
// paint.setStyle(style);
// return paint;
// }
//
// static Marker createTappableMarker(final Context c, int resourceIdentifier,
// LatLong latLong) {
// Bitmap bitmap = new AndroidBitmap(BitmapFactory.decodeResource(c.getResources(), resourceIdentifier));
// bitmap.incrementRefCount();
// return new Marker(latLong, bitmap, 0, -bitmap.getHeight() / 2) {
// @Override
// public boolean onTap(LatLong geoPoint, Point viewPosition,
// Point tapPoint) {
// if (contains(viewPosition, tapPoint)) {
// Toast.makeText(c,
// "The Marker was tapped " + geoPoint.toString(),
// Toast.LENGTH_SHORT).show();
// return true;
// }
// return false;
// }
// };
// }
//
// @SuppressWarnings("deprecation")
// public static Bitmap viewToBitmap(Context c, View view) {
// view.measure(MeasureSpec.getSize(view.getMeasuredWidth()),
// MeasureSpec.getSize(view.getMeasuredHeight()));
// view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
// view.setDrawingCacheEnabled(true);
// Drawable drawable = new BitmapDrawable(c.getResources(),
// android.graphics.Bitmap.createBitmap(view.getDrawingCache()));
// view.setDrawingCacheEnabled(false);
// return AndroidGraphicFactory.convertToBitmap(drawable);
// }
//
// private Utils() {
// throw new IllegalStateException();
// }
//
// }
| import java.util.Map;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.model.Point;
import org.mapsforge.map.model.DisplayModel;
import org.mapsforge.samples.android.R;
import org.mapsforge.samples.android.Utils;
import java.util.HashMap; | /*
* Copyright 2009 Huan Erdao
* Copyright 2014 Martin Vennekamp
* Copyright 2015 mapsforge.org
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android.cluster;
/**
* Utility Class to handle MarkerBitmap
* it handles grid offset to display on the map with offset
*/
public class MarkerBitmap {
private static Map<String, Bitmap> captionViews = new HashMap<String, Bitmap>();
private static Context context;
/**
* bitmap object for normal state icon
*/
protected final Bitmap iconBmpNormal;
/**
* bitmap object for select state icon
*/
protected final Bitmap iconBmpSelect;
/**
* Paint object for drawing icon
*/
protected final Paint paint;
/**
* offset grid of icon in Point.
* if you are using symmetric icon image, it should be half size of width&height.
* adjust this parameter to offset the axis of the image.
*/
protected Point iconOffset;
/**
* maximum item size for the marker.
*/
protected int itemSizeMax;
/**
* text size for icon
*/
protected float textSize;
/**
* NOTE: src_nrm & src_sel must be same bitmap size.
*
* @param src_nrm source Bitmap object for normal state
* @param src_sel source Bitmap object for select state
* @param grid grid point to be offset
* @param textSize text size for icon
* @param maxSize icon size threshold
*/
public MarkerBitmap(Context context, Bitmap src_nrm, Bitmap src_sel,
Point grid, float textSize, int maxSize, Paint paint) {
MarkerBitmap.context = context;
iconBmpNormal = src_nrm;
iconBmpSelect = src_sel;
iconOffset = grid;
this.textSize = textSize * DisplayModel.getDeviceScaleFactor();
itemSizeMax = maxSize;
this.paint = paint;
this.paint.setTextSize(getTextSize());
}
@SuppressWarnings("deprecation")
public static Bitmap getBitmapFromTitle(String title, Paint paint) {
if (!captionViews.containsKey(title)) {
TextView bubbleView = new TextView(context); | // Path: mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/Utils.java
// public final class Utils {
// /**
// * Compatibility method.
// *
// * @param a the current activity
// */
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public static void enableHome(Activity a) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// // Show the Up button in the action bar.
// a.getActionBar().setDisplayHomeAsUpEnabled(true);
// }
// }
//
// /**
// * Compatibility method.
// *
// * @param view the view to set the background on
// * @param background the background
// */
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
// @SuppressWarnings("deprecation")
// public static void setBackground(View view, Drawable background) {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// view.setBackground(background);
// } else {
// view.setBackgroundDrawable(background);
// }
// }
//
// static Marker createMarker(Context c, int resourceIdentifier,
// LatLong latLong) {
// Bitmap bitmap = new AndroidBitmap(BitmapFactory.decodeResource(c.getResources(), resourceIdentifier));
// return new Marker(latLong, bitmap, 0, -bitmap.getHeight() / 2);
// }
//
// static Paint createPaint(int color, int strokeWidth, Style style) {
// Paint paint = AndroidGraphicFactory.INSTANCE.createPaint();
// paint.setColor(color);
// paint.setStrokeWidth(strokeWidth);
// paint.setStyle(style);
// return paint;
// }
//
// static Marker createTappableMarker(final Context c, int resourceIdentifier,
// LatLong latLong) {
// Bitmap bitmap = new AndroidBitmap(BitmapFactory.decodeResource(c.getResources(), resourceIdentifier));
// bitmap.incrementRefCount();
// return new Marker(latLong, bitmap, 0, -bitmap.getHeight() / 2) {
// @Override
// public boolean onTap(LatLong geoPoint, Point viewPosition,
// Point tapPoint) {
// if (contains(viewPosition, tapPoint)) {
// Toast.makeText(c,
// "The Marker was tapped " + geoPoint.toString(),
// Toast.LENGTH_SHORT).show();
// return true;
// }
// return false;
// }
// };
// }
//
// @SuppressWarnings("deprecation")
// public static Bitmap viewToBitmap(Context c, View view) {
// view.measure(MeasureSpec.getSize(view.getMeasuredWidth()),
// MeasureSpec.getSize(view.getMeasuredHeight()));
// view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
// view.setDrawingCacheEnabled(true);
// Drawable drawable = new BitmapDrawable(c.getResources(),
// android.graphics.Bitmap.createBitmap(view.getDrawingCache()));
// view.setDrawingCacheEnabled(false);
// return AndroidGraphicFactory.convertToBitmap(drawable);
// }
//
// private Utils() {
// throw new IllegalStateException();
// }
//
// }
// Path: mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/cluster/MarkerBitmap.java
import java.util.Map;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import org.mapsforge.core.graphics.Bitmap;
import org.mapsforge.core.graphics.Paint;
import org.mapsforge.core.model.Point;
import org.mapsforge.map.model.DisplayModel;
import org.mapsforge.samples.android.R;
import org.mapsforge.samples.android.Utils;
import java.util.HashMap;
/*
* Copyright 2009 Huan Erdao
* Copyright 2014 Martin Vennekamp
* Copyright 2015 mapsforge.org
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android.cluster;
/**
* Utility Class to handle MarkerBitmap
* it handles grid offset to display on the map with offset
*/
public class MarkerBitmap {
private static Map<String, Bitmap> captionViews = new HashMap<String, Bitmap>();
private static Context context;
/**
* bitmap object for normal state icon
*/
protected final Bitmap iconBmpNormal;
/**
* bitmap object for select state icon
*/
protected final Bitmap iconBmpSelect;
/**
* Paint object for drawing icon
*/
protected final Paint paint;
/**
* offset grid of icon in Point.
* if you are using symmetric icon image, it should be half size of width&height.
* adjust this parameter to offset the axis of the image.
*/
protected Point iconOffset;
/**
* maximum item size for the marker.
*/
protected int itemSizeMax;
/**
* text size for icon
*/
protected float textSize;
/**
* NOTE: src_nrm & src_sel must be same bitmap size.
*
* @param src_nrm source Bitmap object for normal state
* @param src_sel source Bitmap object for select state
* @param grid grid point to be offset
* @param textSize text size for icon
* @param maxSize icon size threshold
*/
public MarkerBitmap(Context context, Bitmap src_nrm, Bitmap src_sel,
Point grid, float textSize, int maxSize, Paint paint) {
MarkerBitmap.context = context;
iconBmpNormal = src_nrm;
iconBmpSelect = src_sel;
iconOffset = grid;
this.textSize = textSize * DisplayModel.getDeviceScaleFactor();
itemSizeMax = maxSize;
this.paint = paint;
this.paint.setTextSize(getTextSize());
}
@SuppressWarnings("deprecation")
public static Bitmap getBitmapFromTitle(String title, Paint paint) {
if (!captionViews.containsKey(title)) {
TextView bubbleView = new TextView(context); | Utils.setBackground(bubbleView, context.getResources().getDrawable(R.drawable.caption_background)); |
mapsforge/mapsforge | mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java | // Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlThemeResourceProvider.java
// public interface XmlThemeResourceProvider {
//
// /**
// * @param relativePath a relative path to use as a base for search in the resource provuider
// * @param source a source string parsed out of an XML render theme "src" attribute.
// * @return an InputStream to read the resource data from.
// * @throws IOException if the resource cannot be found or an access error occurred.
// */
// InputStream createInputStream(String relativePath, String source) throws IOException;
// }
| import android.content.res.AssetManager;
import android.text.TextUtils;
import org.mapsforge.core.util.Utils;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlThemeResourceProvider;
import java.io.IOException;
import java.io.InputStream; | /*
* Copyright 2010, 2011, 2012 mapsforge.org
* Copyright 2016-2021 devemux86
* Copyright 2021 eddiemuc
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.android.rendertheme;
/**
* An AssetsRenderTheme allows for customizing the rendering style of the map
* via an XML from the Android assets folder.
*/
public class AssetsRenderTheme implements XmlRenderTheme {
private final AssetManager assetManager;
private final String fileName;
private XmlRenderThemeMenuCallback menuCallback;
private final String relativePathPrefix; | // Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlThemeResourceProvider.java
// public interface XmlThemeResourceProvider {
//
// /**
// * @param relativePath a relative path to use as a base for search in the resource provuider
// * @param source a source string parsed out of an XML render theme "src" attribute.
// * @return an InputStream to read the resource data from.
// * @throws IOException if the resource cannot be found or an access error occurred.
// */
// InputStream createInputStream(String relativePath, String source) throws IOException;
// }
// Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java
import android.content.res.AssetManager;
import android.text.TextUtils;
import org.mapsforge.core.util.Utils;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlThemeResourceProvider;
import java.io.IOException;
import java.io.InputStream;
/*
* Copyright 2010, 2011, 2012 mapsforge.org
* Copyright 2016-2021 devemux86
* Copyright 2021 eddiemuc
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.android.rendertheme;
/**
* An AssetsRenderTheme allows for customizing the rendering style of the map
* via an XML from the Android assets folder.
*/
public class AssetsRenderTheme implements XmlRenderTheme {
private final AssetManager assetManager;
private final String fileName;
private XmlRenderThemeMenuCallback menuCallback;
private final String relativePathPrefix; | private XmlThemeResourceProvider resourceProvider; |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/layer/cache/TileStore.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/graphics/TileBitmap.java
// public interface TileBitmap extends Bitmap {
//
// /**
// * Returns the timestamp of the tile in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.
// * <p/>
// * The timestamp indicates when the tile was created and can be used together with a TTL in order to determine
// * whether to treat it as expired.
// */
// public long getTimestamp();
//
// /**
// * Whether the TileBitmap has expired.
// * <p/>
// * When a tile has expired, the requester should try to replace it with a fresh copy as soon as possible. The
// * expired tile may still be displayed to the user until the fresh copy is available. This may be desirable if
// * obtaining a fresh copy is time-consuming or a fresh copy is currently unavailable (e.g. because no network
// * connection is available for a {@link org.mapsforge.map.layer.download.tilesource.TileSource}).
// *
// * @return {@code true} if expired, {@code false} otherwise.
// */
// public boolean isExpired();
//
// /**
// * Sets the timestamp when this tile will be expired in milliseconds since January 1, 1970 GMT or 0 if this
// * timestamp is unknown.
// * <p/>
// * The timestamp indicates when the tile should be treated it as expired, i.e. {@link #isExpired()} will return
// * {@code true}. For a downloaded tile, pass the value returned by
// * {@link java.net.HttpURLConnection#getExpiration()}, if set by the server. In all other cases you can pass current
// * time plus a fixed TTL in order to have the tile expire after the specified time.
// */
// public void setExpiration(long expiration);
//
// /**
// * Sets the timestamp of the tile in milliseconds since January 1, 1970 GMT.
// * <p/>
// * The timestamp indicates when the information to create the tile was last retrieved from the source. It can be
// * used together with a TTL in order to determine whether to treat it as expired.
// * <p/>
// * The timestamp of a locally rendered tile should be set to the timestamp of the map database used to render it, as
// * returned by {@link org.mapsforge.map.reader.header.MapFileInfo#mapDate}. For a tile read from a disk cache, it
// * should be the file's timestamp. In all other cases (including downloaded tiles), the timestamp should be set to
// * wall clock time (as returned by {@link java.lang.System#currentTimeMillis()}) when the tile is created.
// * <p/>
// * Classes that implement this interface should call {@link java.lang.System#currentTimeMillis()} upon creating an
// * instance, store the result and return it unless {@code setTimestamp()} has been called for that instance.
// */
// public void setTimestamp(long timestamp);
//
// }
| import org.mapsforge.core.graphics.CorruptedInputStreamException;
import org.mapsforge.core.graphics.GraphicFactory;
import org.mapsforge.core.graphics.TileBitmap;
import org.mapsforge.core.util.IOUtils;
import org.mapsforge.map.layer.queue.Job;
import org.mapsforge.map.model.common.Observer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.logging.Logger; | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014 Ludwig M Brinckmann
* Copyright 2019 mg4gh
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.layer.cache;
/**
* A "tilecache" storing map tiles that is prepopulated and never removes any files.
* This tile store uses the standard TMS directory layout of zoomlevel/y/x . To support
* a different directory structure override the findFile method.
*/
public class TileStore implements TileCache {
private final File rootDirectory;
private final GraphicFactory graphicFactory;
private final String suffix;
private static final Logger LOGGER = Logger.getLogger(TileStore.class.getName());
/**
* @param rootDirectory the directory where cached tiles will be stored.
* @param suffix the suffix for stored tiles.
* @param graphicFactory the mapsforge graphic factory to create tile data instances.
* @throws IllegalArgumentException if the root directory cannot be a tile store
*/
public TileStore(File rootDirectory, String suffix, GraphicFactory graphicFactory) {
this.rootDirectory = rootDirectory;
this.graphicFactory = graphicFactory;
this.suffix = suffix;
if (this.rootDirectory == null || !this.rootDirectory.isDirectory() || !this.rootDirectory.canRead()) {
throw new IllegalArgumentException("Root directory must be readable");
}
}
@Override
public synchronized boolean containsKey(Job key) {
return this.findFile(key) != null;
}
@Override
public synchronized void destroy() {
// no-op
}
@Override | // Path: mapsforge-core/src/main/java/org/mapsforge/core/graphics/TileBitmap.java
// public interface TileBitmap extends Bitmap {
//
// /**
// * Returns the timestamp of the tile in milliseconds since January 1, 1970 GMT or 0 if this timestamp is unknown.
// * <p/>
// * The timestamp indicates when the tile was created and can be used together with a TTL in order to determine
// * whether to treat it as expired.
// */
// public long getTimestamp();
//
// /**
// * Whether the TileBitmap has expired.
// * <p/>
// * When a tile has expired, the requester should try to replace it with a fresh copy as soon as possible. The
// * expired tile may still be displayed to the user until the fresh copy is available. This may be desirable if
// * obtaining a fresh copy is time-consuming or a fresh copy is currently unavailable (e.g. because no network
// * connection is available for a {@link org.mapsforge.map.layer.download.tilesource.TileSource}).
// *
// * @return {@code true} if expired, {@code false} otherwise.
// */
// public boolean isExpired();
//
// /**
// * Sets the timestamp when this tile will be expired in milliseconds since January 1, 1970 GMT or 0 if this
// * timestamp is unknown.
// * <p/>
// * The timestamp indicates when the tile should be treated it as expired, i.e. {@link #isExpired()} will return
// * {@code true}. For a downloaded tile, pass the value returned by
// * {@link java.net.HttpURLConnection#getExpiration()}, if set by the server. In all other cases you can pass current
// * time plus a fixed TTL in order to have the tile expire after the specified time.
// */
// public void setExpiration(long expiration);
//
// /**
// * Sets the timestamp of the tile in milliseconds since January 1, 1970 GMT.
// * <p/>
// * The timestamp indicates when the information to create the tile was last retrieved from the source. It can be
// * used together with a TTL in order to determine whether to treat it as expired.
// * <p/>
// * The timestamp of a locally rendered tile should be set to the timestamp of the map database used to render it, as
// * returned by {@link org.mapsforge.map.reader.header.MapFileInfo#mapDate}. For a tile read from a disk cache, it
// * should be the file's timestamp. In all other cases (including downloaded tiles), the timestamp should be set to
// * wall clock time (as returned by {@link java.lang.System#currentTimeMillis()}) when the tile is created.
// * <p/>
// * Classes that implement this interface should call {@link java.lang.System#currentTimeMillis()} upon creating an
// * instance, store the result and return it unless {@code setTimestamp()} has been called for that instance.
// */
// public void setTimestamp(long timestamp);
//
// }
// Path: mapsforge-map/src/main/java/org/mapsforge/map/layer/cache/TileStore.java
import org.mapsforge.core.graphics.CorruptedInputStreamException;
import org.mapsforge.core.graphics.GraphicFactory;
import org.mapsforge.core.graphics.TileBitmap;
import org.mapsforge.core.util.IOUtils;
import org.mapsforge.map.layer.queue.Job;
import org.mapsforge.map.model.common.Observer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.logging.Logger;
/*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2014 Ludwig M Brinckmann
* Copyright 2019 mg4gh
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.map.layer.cache;
/**
* A "tilecache" storing map tiles that is prepopulated and never removes any files.
* This tile store uses the standard TMS directory layout of zoomlevel/y/x . To support
* a different directory structure override the findFile method.
*/
public class TileStore implements TileCache {
private final File rootDirectory;
private final GraphicFactory graphicFactory;
private final String suffix;
private static final Logger LOGGER = Logger.getLogger(TileStore.class.getName());
/**
* @param rootDirectory the directory where cached tiles will be stored.
* @param suffix the suffix for stored tiles.
* @param graphicFactory the mapsforge graphic factory to create tile data instances.
* @throws IllegalArgumentException if the root directory cannot be a tile store
*/
public TileStore(File rootDirectory, String suffix, GraphicFactory graphicFactory) {
this.rootDirectory = rootDirectory;
this.graphicFactory = graphicFactory;
this.suffix = suffix;
if (this.rootDirectory == null || !this.rootDirectory.isDirectory() || !this.rootDirectory.canRead()) {
throw new IllegalArgumentException("Root directory must be readable");
}
}
@Override
public synchronized boolean containsKey(Job key) {
return this.findFile(key) != null;
}
@Override
public synchronized void destroy() {
// no-op
}
@Override | public synchronized TileBitmap get(Job key) { |
mapsforge/mapsforge | mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/StyleMenuMapViewer.java | // Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java
// public class AssetsRenderTheme implements XmlRenderTheme {
//
// private final AssetManager assetManager;
// private final String fileName;
// private XmlRenderThemeMenuCallback menuCallback;
// private final String relativePathPrefix;
// private XmlThemeResourceProvider resourceProvider;
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName) {
// this(assetManager, relativePathPrefix, fileName, null);
// }
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName, XmlRenderThemeMenuCallback menuCallback) {
// this.assetManager = assetManager;
// this.relativePathPrefix = relativePathPrefix;
// this.fileName = fileName;
// this.menuCallback = menuCallback;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// } else if (!(obj instanceof AssetsRenderTheme)) {
// return false;
// }
// AssetsRenderTheme other = (AssetsRenderTheme) obj;
// try {
// if (getRenderThemeAsStream() != other.getRenderThemeAsStream()) {
// return false;
// }
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// if (!Utils.equals(this.relativePathPrefix, other.relativePathPrefix)) {
// return false;
// }
// return true;
// }
//
// @Override
// public XmlRenderThemeMenuCallback getMenuCallback() {
// return this.menuCallback;
// }
//
// @Override
// public String getRelativePathPrefix() {
// return this.relativePathPrefix;
// }
//
// @Override
// public InputStream getRenderThemeAsStream() throws IOException {
// return this.assetManager.open((TextUtils.isEmpty(this.relativePathPrefix) ? "" : this.relativePathPrefix) + this.fileName);
// }
//
// @Override
// public XmlThemeResourceProvider getResourceProvider() {
// return this.resourceProvider;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// InputStream inputStream = null;
// try {
// inputStream = getRenderThemeAsStream();
// } catch (IOException e) {
// e.printStackTrace();
// }
// result = prime * result + ((inputStream == null) ? 0 : inputStream.hashCode());
// result = prime * result + ((this.relativePathPrefix == null) ? 0 : this.relativePathPrefix.hashCode());
// return result;
// }
//
// @Override
// public void setMenuCallback(XmlRenderThemeMenuCallback menuCallback) {
// this.menuCallback = menuCallback;
// }
//
// @Override
// public void setResourceProvider(XmlThemeResourceProvider resourceProvider) {
// this.resourceProvider = resourceProvider;
// }
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
| import android.content.SharedPreferences;
import android.util.Log;
import org.mapsforge.map.android.rendertheme.AssetsRenderTheme;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleLayer;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import java.util.Set; | /*
* Copyright 2013-2014 Ludwig M Brinckmann
* Copyright 2016-2020 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android;
/**
* Load render theme from Android assets folder and show a configuration menu based on stylemenu.
*/
public class StyleMenuMapViewer extends SamplesBaseActivity implements XmlRenderThemeMenuCallback {
@Override | // Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java
// public class AssetsRenderTheme implements XmlRenderTheme {
//
// private final AssetManager assetManager;
// private final String fileName;
// private XmlRenderThemeMenuCallback menuCallback;
// private final String relativePathPrefix;
// private XmlThemeResourceProvider resourceProvider;
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName) {
// this(assetManager, relativePathPrefix, fileName, null);
// }
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName, XmlRenderThemeMenuCallback menuCallback) {
// this.assetManager = assetManager;
// this.relativePathPrefix = relativePathPrefix;
// this.fileName = fileName;
// this.menuCallback = menuCallback;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// } else if (!(obj instanceof AssetsRenderTheme)) {
// return false;
// }
// AssetsRenderTheme other = (AssetsRenderTheme) obj;
// try {
// if (getRenderThemeAsStream() != other.getRenderThemeAsStream()) {
// return false;
// }
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// if (!Utils.equals(this.relativePathPrefix, other.relativePathPrefix)) {
// return false;
// }
// return true;
// }
//
// @Override
// public XmlRenderThemeMenuCallback getMenuCallback() {
// return this.menuCallback;
// }
//
// @Override
// public String getRelativePathPrefix() {
// return this.relativePathPrefix;
// }
//
// @Override
// public InputStream getRenderThemeAsStream() throws IOException {
// return this.assetManager.open((TextUtils.isEmpty(this.relativePathPrefix) ? "" : this.relativePathPrefix) + this.fileName);
// }
//
// @Override
// public XmlThemeResourceProvider getResourceProvider() {
// return this.resourceProvider;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// InputStream inputStream = null;
// try {
// inputStream = getRenderThemeAsStream();
// } catch (IOException e) {
// e.printStackTrace();
// }
// result = prime * result + ((inputStream == null) ? 0 : inputStream.hashCode());
// result = prime * result + ((this.relativePathPrefix == null) ? 0 : this.relativePathPrefix.hashCode());
// return result;
// }
//
// @Override
// public void setMenuCallback(XmlRenderThemeMenuCallback menuCallback) {
// this.menuCallback = menuCallback;
// }
//
// @Override
// public void setResourceProvider(XmlThemeResourceProvider resourceProvider) {
// this.resourceProvider = resourceProvider;
// }
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
// Path: mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/StyleMenuMapViewer.java
import android.content.SharedPreferences;
import android.util.Log;
import org.mapsforge.map.android.rendertheme.AssetsRenderTheme;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleLayer;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import java.util.Set;
/*
* Copyright 2013-2014 Ludwig M Brinckmann
* Copyright 2016-2020 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android;
/**
* Load render theme from Android assets folder and show a configuration menu based on stylemenu.
*/
public class StyleMenuMapViewer extends SamplesBaseActivity implements XmlRenderThemeMenuCallback {
@Override | protected XmlRenderTheme getRenderTheme() { |
mapsforge/mapsforge | mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/StyleMenuMapViewer.java | // Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java
// public class AssetsRenderTheme implements XmlRenderTheme {
//
// private final AssetManager assetManager;
// private final String fileName;
// private XmlRenderThemeMenuCallback menuCallback;
// private final String relativePathPrefix;
// private XmlThemeResourceProvider resourceProvider;
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName) {
// this(assetManager, relativePathPrefix, fileName, null);
// }
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName, XmlRenderThemeMenuCallback menuCallback) {
// this.assetManager = assetManager;
// this.relativePathPrefix = relativePathPrefix;
// this.fileName = fileName;
// this.menuCallback = menuCallback;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// } else if (!(obj instanceof AssetsRenderTheme)) {
// return false;
// }
// AssetsRenderTheme other = (AssetsRenderTheme) obj;
// try {
// if (getRenderThemeAsStream() != other.getRenderThemeAsStream()) {
// return false;
// }
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// if (!Utils.equals(this.relativePathPrefix, other.relativePathPrefix)) {
// return false;
// }
// return true;
// }
//
// @Override
// public XmlRenderThemeMenuCallback getMenuCallback() {
// return this.menuCallback;
// }
//
// @Override
// public String getRelativePathPrefix() {
// return this.relativePathPrefix;
// }
//
// @Override
// public InputStream getRenderThemeAsStream() throws IOException {
// return this.assetManager.open((TextUtils.isEmpty(this.relativePathPrefix) ? "" : this.relativePathPrefix) + this.fileName);
// }
//
// @Override
// public XmlThemeResourceProvider getResourceProvider() {
// return this.resourceProvider;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// InputStream inputStream = null;
// try {
// inputStream = getRenderThemeAsStream();
// } catch (IOException e) {
// e.printStackTrace();
// }
// result = prime * result + ((inputStream == null) ? 0 : inputStream.hashCode());
// result = prime * result + ((this.relativePathPrefix == null) ? 0 : this.relativePathPrefix.hashCode());
// return result;
// }
//
// @Override
// public void setMenuCallback(XmlRenderThemeMenuCallback menuCallback) {
// this.menuCallback = menuCallback;
// }
//
// @Override
// public void setResourceProvider(XmlThemeResourceProvider resourceProvider) {
// this.resourceProvider = resourceProvider;
// }
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
| import android.content.SharedPreferences;
import android.util.Log;
import org.mapsforge.map.android.rendertheme.AssetsRenderTheme;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleLayer;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import java.util.Set; | /*
* Copyright 2013-2014 Ludwig M Brinckmann
* Copyright 2016-2020 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android;
/**
* Load render theme from Android assets folder and show a configuration menu based on stylemenu.
*/
public class StyleMenuMapViewer extends SamplesBaseActivity implements XmlRenderThemeMenuCallback {
@Override
protected XmlRenderTheme getRenderTheme() { | // Path: mapsforge-map-android/src/main/java/org/mapsforge/map/android/rendertheme/AssetsRenderTheme.java
// public class AssetsRenderTheme implements XmlRenderTheme {
//
// private final AssetManager assetManager;
// private final String fileName;
// private XmlRenderThemeMenuCallback menuCallback;
// private final String relativePathPrefix;
// private XmlThemeResourceProvider resourceProvider;
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName) {
// this(assetManager, relativePathPrefix, fileName, null);
// }
//
// /**
// * @param assetManager the Android asset manager.
// * @param relativePathPrefix the prefix for all relative resource paths.
// * @param fileName the path to the XML render theme file.
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// public AssetsRenderTheme(AssetManager assetManager, String relativePathPrefix, String fileName, XmlRenderThemeMenuCallback menuCallback) {
// this.assetManager = assetManager;
// this.relativePathPrefix = relativePathPrefix;
// this.fileName = fileName;
// this.menuCallback = menuCallback;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// } else if (!(obj instanceof AssetsRenderTheme)) {
// return false;
// }
// AssetsRenderTheme other = (AssetsRenderTheme) obj;
// try {
// if (getRenderThemeAsStream() != other.getRenderThemeAsStream()) {
// return false;
// }
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// if (!Utils.equals(this.relativePathPrefix, other.relativePathPrefix)) {
// return false;
// }
// return true;
// }
//
// @Override
// public XmlRenderThemeMenuCallback getMenuCallback() {
// return this.menuCallback;
// }
//
// @Override
// public String getRelativePathPrefix() {
// return this.relativePathPrefix;
// }
//
// @Override
// public InputStream getRenderThemeAsStream() throws IOException {
// return this.assetManager.open((TextUtils.isEmpty(this.relativePathPrefix) ? "" : this.relativePathPrefix) + this.fileName);
// }
//
// @Override
// public XmlThemeResourceProvider getResourceProvider() {
// return this.resourceProvider;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// InputStream inputStream = null;
// try {
// inputStream = getRenderThemeAsStream();
// } catch (IOException e) {
// e.printStackTrace();
// }
// result = prime * result + ((inputStream == null) ? 0 : inputStream.hashCode());
// result = prime * result + ((this.relativePathPrefix == null) ? 0 : this.relativePathPrefix.hashCode());
// return result;
// }
//
// @Override
// public void setMenuCallback(XmlRenderThemeMenuCallback menuCallback) {
// this.menuCallback = menuCallback;
// }
//
// @Override
// public void setResourceProvider(XmlThemeResourceProvider resourceProvider) {
// this.resourceProvider = resourceProvider;
// }
// }
//
// Path: mapsforge-map/src/main/java/org/mapsforge/map/rendertheme/XmlRenderTheme.java
// public interface XmlRenderTheme {
// /**
// * @return the interface callback to create a settings menu on the fly.
// */
// XmlRenderThemeMenuCallback getMenuCallback();
//
// /**
// * @return the prefix for all relative resource paths.
// */
// String getRelativePathPrefix();
//
// /**
// * @return an InputStream to read the render theme data from.
// * @throws IOException if the render theme file cannot be found.
// */
// InputStream getRenderThemeAsStream() throws IOException;
//
// /**
// * @return a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// XmlThemeResourceProvider getResourceProvider();
//
// /**
// * @param menuCallback the interface callback to create a settings menu on the fly.
// */
// void setMenuCallback(XmlRenderThemeMenuCallback menuCallback);
//
// /**
// * @param resourceProvider a custom provider to retrieve resources internally referenced by "src" attribute (e.g. images, icons).
// */
// void setResourceProvider(XmlThemeResourceProvider resourceProvider);
// }
// Path: mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/StyleMenuMapViewer.java
import android.content.SharedPreferences;
import android.util.Log;
import org.mapsforge.map.android.rendertheme.AssetsRenderTheme;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleLayer;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import java.util.Set;
/*
* Copyright 2013-2014 Ludwig M Brinckmann
* Copyright 2016-2020 devemux86
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.samples.android;
/**
* Load render theme from Android assets folder and show a configuration menu based on stylemenu.
*/
public class StyleMenuMapViewer extends SamplesBaseActivity implements XmlRenderThemeMenuCallback {
@Override
protected XmlRenderTheme getRenderTheme() { | return new AssetsRenderTheme(getAssets(), getRenderThemePrefix(), getRenderThemeFile(), this); |
mapsforge/mapsforge | mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java | // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
| import org.mapsforge.core.graphics.*;
import org.mapsforge.core.mapelements.MapElementContainer;
import org.mapsforge.core.model.Point;
import org.mapsforge.core.model.Rectangle;
import org.mapsforge.core.model.Tile;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.rendertheme.RenderContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set; | private void drawCircleContainer(ShapePaintContainer shapePaintContainer) {
CircleContainer circleContainer = (CircleContainer) shapePaintContainer.shapeContainer;
Point point = circleContainer.point;
this.canvas.drawCircle((int) point.x, (int) point.y, (int) circleContainer.radius, shapePaintContainer.paint);
}
private void drawHillshading(HillshadingContainer container) {
canvas.shadeBitmap(container.bitmap, container.hillsRect, container.tileRect, container.magnitude);
}
private void drawPath(RenderContext renderContext, ShapePaintContainer shapePaintContainer, Point[][] coordinates, float dy) {
this.path.clear();
for (Point[] innerList : coordinates) {
Point[] points;
if (dy != 0f) {
points = RendererUtils.parallelPath(innerList, dy);
} else {
points = innerList;
}
if (points.length >= 2) {
Point point = points[0];
this.path.moveTo((float) point.x, (float) point.y);
for (int i = 1; i < points.length; ++i) {
point = points[i];
this.path.lineTo((int) point.x, (int) point.y);
}
}
}
| // Path: mapsforge-core/src/main/java/org/mapsforge/core/util/Parameters.java
// public final class Parameters {
//
// public enum ParentTilesRendering {QUALITY, SPEED, OFF}
//
// public enum SymbolScaling {ALL, POI}
//
// /**
// * If true will use anti-aliasing in rendering.
// */
// public static boolean ANTI_ALIASING = true;
//
// /**
// * If true the <code>FrameBufferHA3</code> will be used instead of default <code>FrameBufferHA2}</code>.
// */
// public static boolean FRAME_BUFFER_HA3 = true;
//
// /**
// * Process layer scroll events.
// */
// public static boolean LAYER_SCROLL_EVENT = false;
//
// /**
// * Maximum buffer size for map files.
// */
// public static int MAXIMUM_BUFFER_SIZE = 10000000;
//
// /**
// * The default number of threads is one greater than the number of processors, as one thread is
// * likely to be blocked on I/O reading map data. Technically this value can change to a better
// * implementation, maybe one that also takes the available memory into account would be good.
// * For stability reasons (see #591), we set default number of threads to 1.
// */
// public static int NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
//
// /**
// * Parent tiles rendering mode.
// */
// public static ParentTilesRendering PARENT_TILES_RENDERING = ParentTilesRendering.QUALITY;
//
// /**
// * If square frame buffer is enabled, the frame buffer allocated for drawing will be
// * large enough for drawing in either orientation, so no change is needed when the device
// * orientation changes. To avoid overly large frame buffers, the aspect ratio for this policy
// * determines when this will be used.
// */
// public static boolean SQUARE_FRAME_BUFFER = true;
//
// /**
// * Symbol scaling mode.
// */
// public static SymbolScaling SYMBOL_SCALING = SymbolScaling.POI;
//
// /**
// * Validate coordinates.
// */
// public static boolean VALIDATE_COORDINATES = true;
//
// private Parameters() {
// throw new IllegalStateException();
// }
// }
// Path: mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/CanvasRasterer.java
import org.mapsforge.core.graphics.*;
import org.mapsforge.core.mapelements.MapElementContainer;
import org.mapsforge.core.model.Point;
import org.mapsforge.core.model.Rectangle;
import org.mapsforge.core.model.Tile;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.rendertheme.RenderContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
private void drawCircleContainer(ShapePaintContainer shapePaintContainer) {
CircleContainer circleContainer = (CircleContainer) shapePaintContainer.shapeContainer;
Point point = circleContainer.point;
this.canvas.drawCircle((int) point.x, (int) point.y, (int) circleContainer.radius, shapePaintContainer.paint);
}
private void drawHillshading(HillshadingContainer container) {
canvas.shadeBitmap(container.bitmap, container.hillsRect, container.tileRect, container.magnitude);
}
private void drawPath(RenderContext renderContext, ShapePaintContainer shapePaintContainer, Point[][] coordinates, float dy) {
this.path.clear();
for (Point[] innerList : coordinates) {
Point[] points;
if (dy != 0f) {
points = RendererUtils.parallelPath(innerList, dy);
} else {
points = innerList;
}
if (points.length >= 2) {
Point point = points[0];
this.path.moveTo((float) point.x, (float) point.y);
for (int i = 1; i < points.length; ++i) {
point = points[i];
this.path.lineTo((int) point.x, (int) point.y);
}
}
}
| if (Parameters.NUMBER_OF_THREADS > 1) { |
FabianTerhorst/DrawerOverlayService | app/src/main/java/com/google/android/libraries/i/LauncherOverlayInterfaceBinder.java | // Path: app/src/main/java/com/google/android/a/LauncherOverlayBinder.java
// public class LauncherOverlayBinder extends Binder implements IInterface {
// public IBinder asBinder() {
// return this;
// }
//
// public final boolean a(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
// if (i > 16777215) {
// return super.onTransact(i, parcel, parcel2, i2);
// }
// parcel.enforceInterface(getInterfaceDescriptor());
// return false;
// }
// }
//
// Path: app/src/main/java/com/google/android/a/c.java
// public class c {
// public static final ClassLoader bHi = c.class.getClassLoader();
//
// private c() {
// }
//
// public static boolean a(Parcel parcel) {
// return parcel.readInt() == 1;
// }
//
// public static void a(Parcel parcel, boolean z) {
// parcel.writeInt(z ? 1 : 0);
// }
//
// public static Parcelable a(Parcel parcel, Creator creator) {
// if (parcel.readInt() == 0) {
// return null;
// }
// return (Parcelable) creator.createFromParcel(parcel);
// }
//
// public static void a(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 0);
// }
//
// public static void b(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 1);
// }
//
// public static void a(Parcel parcel, IInterface iInterface) {
// if (iInterface == null) {
// parcel.writeStrongBinder(null);
// } else {
// parcel.writeStrongBinder(iInterface.asBinder());
// }
// }
//
// public static HashMap b(Parcel parcel) {
// return parcel.readHashMap(bHi);
// }
// }
//
// Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
| import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.WindowManager.LayoutParams;
import com.google.android.a.LauncherOverlayBinder;
import com.google.android.a.c;
import com.google.android.libraries.material.progress.u; | package com.google.android.libraries.i;
//import com.google.android.gms.dynamite.descriptors.com.google.android.gms.ads.dynamite.ModuleDescriptor;
public abstract class LauncherOverlayInterfaceBinder extends LauncherOverlayBinder implements a {
public LauncherOverlayInterfaceBinder() {
attachInterface(this, "com.google.android.libraries.launcherclient.ILauncherOverlay");
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
d dVar = null;
if (a(i, parcel, parcel2, i2)) {
return true;
}
IBinder readStrongBinder;
IInterface queryLocalInterface;
boolean HC;
switch (i) {
case 1:
cnK();
break;
case 2:
aL(parcel.readFloat());
break;
case 3:
cnL();
break; | // Path: app/src/main/java/com/google/android/a/LauncherOverlayBinder.java
// public class LauncherOverlayBinder extends Binder implements IInterface {
// public IBinder asBinder() {
// return this;
// }
//
// public final boolean a(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
// if (i > 16777215) {
// return super.onTransact(i, parcel, parcel2, i2);
// }
// parcel.enforceInterface(getInterfaceDescriptor());
// return false;
// }
// }
//
// Path: app/src/main/java/com/google/android/a/c.java
// public class c {
// public static final ClassLoader bHi = c.class.getClassLoader();
//
// private c() {
// }
//
// public static boolean a(Parcel parcel) {
// return parcel.readInt() == 1;
// }
//
// public static void a(Parcel parcel, boolean z) {
// parcel.writeInt(z ? 1 : 0);
// }
//
// public static Parcelable a(Parcel parcel, Creator creator) {
// if (parcel.readInt() == 0) {
// return null;
// }
// return (Parcelable) creator.createFromParcel(parcel);
// }
//
// public static void a(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 0);
// }
//
// public static void b(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 1);
// }
//
// public static void a(Parcel parcel, IInterface iInterface) {
// if (iInterface == null) {
// parcel.writeStrongBinder(null);
// } else {
// parcel.writeStrongBinder(iInterface.asBinder());
// }
// }
//
// public static HashMap b(Parcel parcel) {
// return parcel.readHashMap(bHi);
// }
// }
//
// Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
// Path: app/src/main/java/com/google/android/libraries/i/LauncherOverlayInterfaceBinder.java
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.WindowManager.LayoutParams;
import com.google.android.a.LauncherOverlayBinder;
import com.google.android.a.c;
import com.google.android.libraries.material.progress.u;
package com.google.android.libraries.i;
//import com.google.android.gms.dynamite.descriptors.com.google.android.gms.ads.dynamite.ModuleDescriptor;
public abstract class LauncherOverlayInterfaceBinder extends LauncherOverlayBinder implements a {
public LauncherOverlayInterfaceBinder() {
attachInterface(this, "com.google.android.libraries.launcherclient.ILauncherOverlay");
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
d dVar = null;
if (a(i, parcel, parcel2, i2)) {
return true;
}
IBinder readStrongBinder;
IInterface queryLocalInterface;
boolean HC;
switch (i) {
case 1:
cnK();
break;
case 2:
aL(parcel.readFloat());
break;
case 3:
cnL();
break; | case u.uKO /*4*/: |
FabianTerhorst/DrawerOverlayService | app/src/main/java/com/google/android/libraries/i/LauncherOverlayInterfaceBinder.java | // Path: app/src/main/java/com/google/android/a/LauncherOverlayBinder.java
// public class LauncherOverlayBinder extends Binder implements IInterface {
// public IBinder asBinder() {
// return this;
// }
//
// public final boolean a(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
// if (i > 16777215) {
// return super.onTransact(i, parcel, parcel2, i2);
// }
// parcel.enforceInterface(getInterfaceDescriptor());
// return false;
// }
// }
//
// Path: app/src/main/java/com/google/android/a/c.java
// public class c {
// public static final ClassLoader bHi = c.class.getClassLoader();
//
// private c() {
// }
//
// public static boolean a(Parcel parcel) {
// return parcel.readInt() == 1;
// }
//
// public static void a(Parcel parcel, boolean z) {
// parcel.writeInt(z ? 1 : 0);
// }
//
// public static Parcelable a(Parcel parcel, Creator creator) {
// if (parcel.readInt() == 0) {
// return null;
// }
// return (Parcelable) creator.createFromParcel(parcel);
// }
//
// public static void a(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 0);
// }
//
// public static void b(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 1);
// }
//
// public static void a(Parcel parcel, IInterface iInterface) {
// if (iInterface == null) {
// parcel.writeStrongBinder(null);
// } else {
// parcel.writeStrongBinder(iInterface.asBinder());
// }
// }
//
// public static HashMap b(Parcel parcel) {
// return parcel.readHashMap(bHi);
// }
// }
//
// Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
| import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.WindowManager.LayoutParams;
import com.google.android.a.LauncherOverlayBinder;
import com.google.android.a.c;
import com.google.android.libraries.material.progress.u; | package com.google.android.libraries.i;
//import com.google.android.gms.dynamite.descriptors.com.google.android.gms.ads.dynamite.ModuleDescriptor;
public abstract class LauncherOverlayInterfaceBinder extends LauncherOverlayBinder implements a {
public LauncherOverlayInterfaceBinder() {
attachInterface(this, "com.google.android.libraries.launcherclient.ILauncherOverlay");
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
d dVar = null;
if (a(i, parcel, parcel2, i2)) {
return true;
}
IBinder readStrongBinder;
IInterface queryLocalInterface;
boolean HC;
switch (i) {
case 1:
cnK();
break;
case 2:
aL(parcel.readFloat());
break;
case 3:
cnL();
break;
case u.uKO /*4*/: | // Path: app/src/main/java/com/google/android/a/LauncherOverlayBinder.java
// public class LauncherOverlayBinder extends Binder implements IInterface {
// public IBinder asBinder() {
// return this;
// }
//
// public final boolean a(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
// if (i > 16777215) {
// return super.onTransact(i, parcel, parcel2, i2);
// }
// parcel.enforceInterface(getInterfaceDescriptor());
// return false;
// }
// }
//
// Path: app/src/main/java/com/google/android/a/c.java
// public class c {
// public static final ClassLoader bHi = c.class.getClassLoader();
//
// private c() {
// }
//
// public static boolean a(Parcel parcel) {
// return parcel.readInt() == 1;
// }
//
// public static void a(Parcel parcel, boolean z) {
// parcel.writeInt(z ? 1 : 0);
// }
//
// public static Parcelable a(Parcel parcel, Creator creator) {
// if (parcel.readInt() == 0) {
// return null;
// }
// return (Parcelable) creator.createFromParcel(parcel);
// }
//
// public static void a(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 0);
// }
//
// public static void b(Parcel parcel, Parcelable parcelable) {
// if (parcelable == null) {
// parcel.writeInt(0);
// return;
// }
// parcel.writeInt(1);
// parcelable.writeToParcel(parcel, 1);
// }
//
// public static void a(Parcel parcel, IInterface iInterface) {
// if (iInterface == null) {
// parcel.writeStrongBinder(null);
// } else {
// parcel.writeStrongBinder(iInterface.asBinder());
// }
// }
//
// public static HashMap b(Parcel parcel) {
// return parcel.readHashMap(bHi);
// }
// }
//
// Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
// Path: app/src/main/java/com/google/android/libraries/i/LauncherOverlayInterfaceBinder.java
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.WindowManager.LayoutParams;
import com.google.android.a.LauncherOverlayBinder;
import com.google.android.a.c;
import com.google.android.libraries.material.progress.u;
package com.google.android.libraries.i;
//import com.google.android.gms.dynamite.descriptors.com.google.android.gms.ads.dynamite.ModuleDescriptor;
public abstract class LauncherOverlayInterfaceBinder extends LauncherOverlayBinder implements a {
public LauncherOverlayInterfaceBinder() {
attachInterface(this, "com.google.android.libraries.launcherclient.ILauncherOverlay");
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {//Todo: throws is new
d dVar = null;
if (a(i, parcel, parcel2, i2)) {
return true;
}
IBinder readStrongBinder;
IInterface queryLocalInterface;
boolean HC;
switch (i) {
case 1:
cnK();
break;
case 2:
aL(parcel.readFloat());
break;
case 3:
cnL();
break;
case u.uKO /*4*/: | LayoutParams layoutParams = (LayoutParams) c.a(parcel, LayoutParams.CREATOR); |
FabianTerhorst/DrawerOverlayService | app/src/main/java/com/google/android/libraries/gsa/d/a/OverlayControllerCallback.java | // Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
| import android.content.ComponentName;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import com.google.android.libraries.material.progress.u;
import java.io.PrintWriter; | overlayControllerVar2 = this.overlayController;
overlayControllerVar2.uoa = (com.google.android.libraries.i.d) pair.second;
overlayControllerVar2.bP(true);
this.overlayControllerBinder.a((com.google.android.libraries.i.d) pair.second, this.uor);
return true;
} catch (Throwable e) {
Log.d("OverlaySController", "Error creating overlay window", e);
Message obtain = Message.obtain();
obtain.what = 2;
handleMessage(obtain);
obtain.recycle();
return true;
}
case 1:
if (this.overlayController == null) {
return true;
}
this.overlayController.BJ((Integer) message.obj);
return true;
case 2:
if (this.overlayController == null) {
return true;
}
com.google.android.libraries.i.d cnC = this.overlayController.cnC();
this.overlayController = null;
if (message.arg1 != 0) {
return true;
}
this.overlayControllerBinder.a(cnC, 0);
return true; | // Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
// Path: app/src/main/java/com/google/android/libraries/gsa/d/a/OverlayControllerCallback.java
import android.content.ComponentName;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import com.google.android.libraries.material.progress.u;
import java.io.PrintWriter;
overlayControllerVar2 = this.overlayController;
overlayControllerVar2.uoa = (com.google.android.libraries.i.d) pair.second;
overlayControllerVar2.bP(true);
this.overlayControllerBinder.a((com.google.android.libraries.i.d) pair.second, this.uor);
return true;
} catch (Throwable e) {
Log.d("OverlaySController", "Error creating overlay window", e);
Message obtain = Message.obtain();
obtain.what = 2;
handleMessage(obtain);
obtain.recycle();
return true;
}
case 1:
if (this.overlayController == null) {
return true;
}
this.overlayController.BJ((Integer) message.obj);
return true;
case 2:
if (this.overlayController == null) {
return true;
}
com.google.android.libraries.i.d cnC = this.overlayController.cnC();
this.overlayController = null;
if (message.arg1 != 0) {
return true;
}
this.overlayControllerBinder.a(cnC, 0);
return true; | case u.uKQ /*6*/: |
FabianTerhorst/DrawerOverlayService | app/src/main/java/com/google/android/libraries/gsa/d/a/MinusOneOverlayCallback.java | // Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
| import android.content.res.Configuration;
import android.os.Message;
import com.google.android.libraries.material.progress.u;
import java.io.PrintWriter; | public final void dump(PrintWriter printWriter, String str) {
printWriter.println(String.valueOf(str).concat("MinusOneOverlayCallback"));
super.dump(printWriter, str);
}
public final boolean handleMessage(Message message) {
if (super.handleMessage(message)) {
return true;
}
OverlayController overlayControllerVar;
long when;
switch (message.what) {
case 3:
if (this.overlayController != null) {
overlayControllerVar = this.overlayController;
when = message.getWhen();
if (!overlayControllerVar.cnD()) {
SlidingPanelLayout slidingPanelLayoutVar = overlayControllerVar.slidingPanelLayout;
if (slidingPanelLayoutVar.uoC < slidingPanelLayoutVar.mTouchSlop) {
overlayControllerVar.slidingPanelLayout.BM(0);
overlayControllerVar.mAcceptExternalMove = true;
overlayControllerVar.unX = 0;
overlayControllerVar.slidingPanelLayout.mForceDrag = true;
overlayControllerVar.obZ = when - 30;
overlayControllerVar.b(0, overlayControllerVar.unX, overlayControllerVar.obZ);
overlayControllerVar.b(2, overlayControllerVar.unX, when);
}
}
}
return true; | // Path: app/src/main/java/com/google/android/libraries/material/progress/u.java
// public final class u {
// public static final int[] FontFamily = new int[]{2130772442, 2130772443, 2130772444, 2130772445, 2130772446, 2130772447};
// public static final int[] FontFamilyFont = new int[]{2130772448, 2130772449, 2130772450};
// public static final int[] bTM = new int[]{2130772063, 2130772064};
// public static final int[] bTN = new int[]{2130772063, 2130772064, 2130772967, 2130772968, 2130772969, 2130772970, 2130772971, 2130772972};
// public static final int uKM = 0;
// public static final int uKN = 1;
// public static final int uKO = 4;
// public static final int uKP = 3;
// public static final int uKQ = 6;
// public static final int uKR = 7;
// public static final int uKS = 5;
// public static final int uKT = 2;
// }
// Path: app/src/main/java/com/google/android/libraries/gsa/d/a/MinusOneOverlayCallback.java
import android.content.res.Configuration;
import android.os.Message;
import com.google.android.libraries.material.progress.u;
import java.io.PrintWriter;
public final void dump(PrintWriter printWriter, String str) {
printWriter.println(String.valueOf(str).concat("MinusOneOverlayCallback"));
super.dump(printWriter, str);
}
public final boolean handleMessage(Message message) {
if (super.handleMessage(message)) {
return true;
}
OverlayController overlayControllerVar;
long when;
switch (message.what) {
case 3:
if (this.overlayController != null) {
overlayControllerVar = this.overlayController;
when = message.getWhen();
if (!overlayControllerVar.cnD()) {
SlidingPanelLayout slidingPanelLayoutVar = overlayControllerVar.slidingPanelLayout;
if (slidingPanelLayoutVar.uoC < slidingPanelLayoutVar.mTouchSlop) {
overlayControllerVar.slidingPanelLayout.BM(0);
overlayControllerVar.mAcceptExternalMove = true;
overlayControllerVar.unX = 0;
overlayControllerVar.slidingPanelLayout.mForceDrag = true;
overlayControllerVar.obZ = when - 30;
overlayControllerVar.b(0, overlayControllerVar.unX, overlayControllerVar.obZ);
overlayControllerVar.b(2, overlayControllerVar.unX, when);
}
}
}
return true; | case u.uKO /*4*/: |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
| import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import org.apache.jena.rdf.model.Model; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.interfaces;
/**
* Interface that represents a NIF and Stanford NLP token.
*
* @author Julien Plu
*/
public interface Token {
void nextToken(final Token newNextToken);
int index();
String text();
int start();
int end();
| // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import org.apache.jena.rdf.model.Model;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.interfaces;
/**
* Interface that represents a NIF and Stanford NLP token.
*
* @author Julien Plu
*/
public interface Token {
void nextToken(final Token newNextToken);
int index();
String text();
int start();
int end();
| Model rdfModel(final String tool, final NlpProcess process, final String host); |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class SentenceImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImplTest.class);
public SentenceImplTest() {
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a NER annotation and a next {@link Sentence}.
*/
@Test
public final void testRdfModelforNerWithNextSentence() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class SentenceImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImplTest.class);
public SentenceImplTest() {
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a NER annotation and a next {@link Sentence}.
*/
@Test
public final void testRdfModelforNerWithNextSentence() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class SentenceImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImplTest.class);
public SentenceImplTest() {
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a NER annotation and a next {@link Sentence}.
*/
@Test
public final void testRdfModelforNerWithNextSentence() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class SentenceImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImplTest.class);
public SentenceImplTest() {
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a NER annotation and a next {@link Sentence}.
*/
@Test
public final void testRdfModelforNerWithNextSentence() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | 0, 40, 1, NullSentence.getInstance()); |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "referenceContext"),
ResourceFactory.createResource(base + "/context#char=" + context.start() + ','
+ context.end()));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "anchorOf"),
ResourceFactory.createTypedLiteral("She is very stunning."));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "previousSentence"),
ResourceFactory.createResource(base + "/sentence#char=" + sentence.start() + ','
+ sentence.end()));
Assert.assertTrue("Issue to create the model for a Sentence with a previous Sentence",
model.isIsomorphicWith(sentence2.rdfModel("stanfordnlp", NlpProcess.NER,
"http://127.0.0.1")));
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a POS annotation.
*/
@Test
public final void testRdfModelforPos() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "referenceContext"),
ResourceFactory.createResource(base + "/context#char=" + context.start() + ','
+ context.end()));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "anchorOf"),
ResourceFactory.createTypedLiteral("She is very stunning."));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "previousSentence"),
ResourceFactory.createResource(base + "/sentence#char=" + sentence.start() + ','
+ sentence.end()));
Assert.assertTrue("Issue to create the model for a Sentence with a previous Sentence",
model.isIsomorphicWith(sentence2.rdfModel("stanfordnlp", NlpProcess.NER,
"http://127.0.0.1")));
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a POS annotation.
*/
@Test
public final void testRdfModelforPos() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | final Token token = new TokenImpl("My", "PRP$", 0, 2, NullToken.getInstance(), context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "referenceContext"),
ResourceFactory.createResource(base + "/context#char=" + context.start() + ','
+ context.end()));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "anchorOf"),
ResourceFactory.createTypedLiteral("She is very stunning."));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "previousSentence"),
ResourceFactory.createResource(base + "/sentence#char=" + sentence.start() + ','
+ sentence.end()));
Assert.assertTrue("Issue to create the model for a Sentence with a previous Sentence",
model.isIsomorphicWith(sentence2.rdfModel("stanfordnlp", NlpProcess.NER,
"http://127.0.0.1")));
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a POS annotation.
*/
@Test
public final void testRdfModelforPos() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "referenceContext"),
ResourceFactory.createResource(base + "/context#char=" + context.start() + ','
+ context.end()));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "anchorOf"),
ResourceFactory.createTypedLiteral("She is very stunning."));
model.add(ResourceFactory.createResource(base + "/sentence#char=41,62"),
ResourceFactory.createProperty(nif + "previousSentence"),
ResourceFactory.createResource(base + "/sentence#char=" + sentence.start() + ','
+ sentence.end()));
Assert.assertTrue("Issue to create the model for a Sentence with a previous Sentence",
model.isIsomorphicWith(sentence2.rdfModel("stanfordnlp", NlpProcess.NER,
"http://127.0.0.1")));
}
/**
* Test the {@link SentenceImpl#rdfModel(String, NlpProcess, String)} method with a
* {@link Sentence} that has a POS annotation.
*/
@Test
public final void testRdfModelforPos() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | final Token token = new TokenImpl("My", "PRP$", 0, 2, NullToken.getInstance(), context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/EntityTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class EntityTest {
static final Logger LOGGER = LoggerFactory.getLogger(EntityTest.class);
public EntityTest() {
}
/**
* Test {@link Entity#rdfModel(String, String)} method of an {@link Entity}.
*/
@Test
public final void testRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/EntityTest.java
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class EntityTest {
static final Logger LOGGER = LoggerFactory.getLogger(EntityTest.class);
public EntityTest() {
}
/**
* Test {@link Entity#rdfModel(String, String)} method of an {@link Entity}.
*/
@Test
public final void testRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/EntityTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class EntityTest {
static final Logger LOGGER = LoggerFactory.getLogger(EntityTest.class);
public EntityTest() {
}
/**
* Test {@link Entity#rdfModel(String, String)} method of an {@link Entity}.
*/
@Test
public final void testRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/EntityTest.java
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class EntityTest {
static final Logger LOGGER = LoggerFactory.getLogger(EntityTest.class);
public EntityTest() {
}
/**
* Test {@link Entity#rdfModel(String, String)} method of an {@link Entity}.
*/
@Test
public final void testRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | 0, 40, 1, NullSentence.getInstance()); |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
| import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.nullobjects;
/**
* Null object that represents a null token.
*
* @author Julien Plu
*/
public final class NullToken implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
private static final NullToken INSTANCE = new NullToken();
public static NullToken getInstance() {
return NullToken.INSTANCE;
}
private NullToken() {
}
@Override
public void nextToken(final Token newNextToken) {
throw new UnsupportedOperationException("Not imlpemented");
}
@Override
public int index() {
return -1;
}
@Override
public String text() {
return null;
}
@Override
public int start() {
return 0;
}
@Override
public int end() {
return 0;
}
@Override | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.nullobjects;
/**
* Null object that represents a null token.
*
* @author Julien Plu
*/
public final class NullToken implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
private static final NullToken INSTANCE = new NullToken();
public static NullToken getInstance() {
return NullToken.INSTANCE;
}
private NullToken() {
}
@Override
public void nextToken(final Token newNextToken) {
throw new UnsupportedOperationException("Not imlpemented");
}
@Override
public int index() {
return -1;
}
@Override
public String text() {
return null;
}
@Override
public int start() {
return 0;
}
@Override
public int end() {
return 0;
}
@Override | public Model rdfModel(final String tool, final NlpProcess process, final String host) { |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Entity.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
| import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF Entity that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Entity {
static final Logger LOGGER = LoggerFactory.getLogger(Entity.class);
private final String text;
private final String type; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Entity.java
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF Entity that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Entity {
static final Logger LOGGER = LoggerFactory.getLogger(Entity.class);
private final String text;
private final String type; | private final Sentence sentence; |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Coref.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
| import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class Coref {
static final Logger LOGGER = LoggerFactory.getLogger(Coref.class);
private final String coreference;
private final String head;
private final int startHead;
private final int endHead;
private final int start;
private final int end; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Coref.java
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class Coref {
static final Logger LOGGER = LoggerFactory.getLogger(Coref.class);
private final String coreference;
private final String head;
private final int startHead;
private final int endHead;
private final int start;
private final int end; | private final Sentence sentence; |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF token that is aligned to the corresponding Stanford NLP annotations.
*
* @author Julien Plu
*/
public class TokenImpl implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImpl.class);
private final String text;
private final String tag;
private final int start;
private final int end;
private final Token previousToken;
private Token nextToken;
private final Context context; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF token that is aligned to the corresponding Stanford NLP annotations.
*
* @author Julien Plu
*/
public class TokenImpl implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImpl.class);
private final String text;
private final String tag;
private final int start;
private final int end;
private final Token previousToken;
private Token nextToken;
private final Context context; | private final Sentence sentence; |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF token that is aligned to the corresponding Stanford NLP annotations.
*
* @author Julien Plu
*/
public class TokenImpl implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImpl.class);
private final String text;
private final String tag;
private final int start;
private final int end;
private final Token previousToken;
private Token nextToken;
private final Context context;
private final Sentence sentence;
private final int index;
/**
* TokenImpl constructor.
*
* @param newText Text of the token.
* @param newTag Tag of the token.
* @param newStart The start offset of the token.
* @param newEnd The end offset of the token.
* @param newPreviousToken Previous token in the sentence. Null token if none exists.
* @param newContext The context where the token is.
* @param newSentence The sentence where the token is.
* @param newIndex Index of the token in the sentence.
*/
public TokenImpl(final String newText, final String newTag, final int newStart, final int newEnd,
final Token newPreviousToken, final Context newContext,
final Sentence newSentence, final int newIndex) {
this.text = newText;
this.tag = newTag;
this.start = newStart;
this.end = newEnd;
this.previousToken = newPreviousToken; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF token that is aligned to the corresponding Stanford NLP annotations.
*
* @author Julien Plu
*/
public class TokenImpl implements Token {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImpl.class);
private final String text;
private final String tag;
private final int start;
private final int end;
private final Token previousToken;
private Token nextToken;
private final Context context;
private final Sentence sentence;
private final int index;
/**
* TokenImpl constructor.
*
* @param newText Text of the token.
* @param newTag Tag of the token.
* @param newStart The start offset of the token.
* @param newEnd The end offset of the token.
* @param newPreviousToken Previous token in the sentence. Null token if none exists.
* @param newContext The context where the token is.
* @param newSentence The sentence where the token is.
* @param newIndex Index of the token in the sentence.
*/
public TokenImpl(final String newText, final String newTag, final int newStart, final int newEnd,
final Token newPreviousToken, final Context newContext,
final Sentence newSentence, final int newIndex) {
this.text = newText;
this.tag = newTag;
this.start = newStart;
this.end = newEnd;
this.previousToken = newPreviousToken; | this.nextToken = NullToken.getInstance(); |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF; | }
@Override
public final void nextToken(final Token newNextToken) {
if (this.nextToken.index() == -1) {
this.nextToken = newNextToken;
}
}
@Override
public final int index() {
return this.index;
}
@Override
public final String text() {
return this.text;
}
@Override
public final int start() {
return this.start;
}
@Override
public final int end() {
return this.end;
}
@Override | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImpl.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
}
@Override
public final void nextToken(final Token newNextToken) {
if (this.nextToken.index() == -1) {
this.nextToken = newNextToken;
}
}
@Override
public final int index() {
return this.index;
}
@Override
public final String text() {
return this.text;
}
@Override
public final int start() {
return this.start;
}
@Override
public final int end() {
return this.end;
}
@Override | public final Model rdfModel(final String tool, final NlpProcess process, final String host) { |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImpl.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF sentence that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class SentenceImpl implements Sentence {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImpl.class);
private final String text;
private final Context context; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImpl.java
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF sentence that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class SentenceImpl implements Sentence {
static final Logger LOGGER = LoggerFactory.getLogger(SentenceImpl.class);
private final String text;
private final Context context; | private final List<Token> tokens; |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImpl.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype; | }
@Override
public final void nextSentence(final Sentence newNextSentence) {
if (this.nextSentence.index() == -1) {
this.nextSentence = newNextSentence;
}
}
@Override
public final List<Entity> entities() {
return Collections.unmodifiableList(this.entities);
}
@Override
public final int index() {
return this.index;
}
@Override
public final int start() {
return this.start;
}
@Override
public final int end() {
return this.end;
}
@Override | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/SentenceImpl.java
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.jena.datatypes.xsd.XSDDatatype;
}
@Override
public final void nextSentence(final Sentence newNextSentence) {
if (this.nextSentence.index() == -1) {
this.nextSentence = newNextSentence;
}
}
@Override
public final List<Entity> entities() {
return Collections.unmodifiableList(this.entities);
}
@Override
public final int index() {
return this.index;
}
@Override
public final int start() {
return this.start;
}
@Override
public final int end() {
return this.end;
}
@Override | public final Model rdfModel(final String tool, final NlpProcess process, final String host) { |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/CorefTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.junit.Assert;
import org.junit.Test; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class CorefTest {
/**
* Test {@link Coref#equals(Object)} method.
*/
@Test
public final void testEquals() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Context context2 = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 60); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/CorefTest.java
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.junit.Assert;
import org.junit.Test;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class CorefTest {
/**
* Test {@link Coref#equals(Object)} method.
*/
@Test
public final void testEquals() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Context context2 = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 60); | final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/CorefTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.junit.Assert;
import org.junit.Test; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class CorefTest {
/**
* Test {@link Coref#equals(Object)} method.
*/
@Test
public final void testEquals() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Context context2 = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 60);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/CorefTest.java
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import org.junit.Assert;
import org.junit.Test;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class CorefTest {
/**
* Test {@link Coref#equals(Object)} method.
*/
@Test
public final void testEquals() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Context context2 = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 60);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | 0, 40, 1, NullSentence.getInstance()); |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Context.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
| import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF context that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Context {
static final Logger LOGGER = LoggerFactory.getLogger(Context.class);
private final String text;
private final int start;
private final int end; | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Context.java
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF context that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Context {
static final Logger LOGGER = LoggerFactory.getLogger(Context.class);
private final String text;
private final int start;
private final int end; | private final List<Sentence> sentences; |
jplu/stanfordNLPRESTAPI | src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Context.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
| import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF context that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Context {
static final Logger LOGGER = LoggerFactory.getLogger(Context.class);
private final String text;
private final int start;
private final int end;
private final List<Sentence> sentences;
/**
* Context constructor.
*
* @param newText Text that represents the context.
* @param newStart Start offset of the context.
* @param newEnd End offset of the context.
*/
public Context(final String newText, final int newStart, final int newEnd) {
this.sentences = new ArrayList<>();
this.text = newText;
this.start = newStart;
this.end = newEnd;
}
public final int start() {
return this.start;
}
public final int end() {
return this.end;
}
public final void addSentence(final Sentence newSentence) {
this.sentences.add(newSentence);
}
public final String text() {
return this.text;
}
public final List<Sentence> sentences() {
return Collections.unmodifiableList(this.sentences);
}
/**
* Turn the context into RDF model.
*
* @param tool Tool used to extract the context.
* @param process Process required as RDF model.
* @param host Host from where is hosted the app.
*
* @return RDF model in NIF of the context.
*/ | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/datatypes/Context.java
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* This class represents a NIF context that is aligned to the corresponding Stanford NLP
* annotations.
*
* @author Julien Plu
*/
public class Context {
static final Logger LOGGER = LoggerFactory.getLogger(Context.class);
private final String text;
private final int start;
private final int end;
private final List<Sentence> sentences;
/**
* Context constructor.
*
* @param newText Text that represents the context.
* @param newStart Start offset of the context.
* @param newEnd End offset of the context.
*/
public Context(final String newText, final int newStart, final int newEnd) {
this.sentences = new ArrayList<>();
this.text = newText;
this.start = newStart;
this.end = newEnd;
}
public final int start() {
return this.start;
}
public final int end() {
return this.end;
}
public final void addSentence(final Sentence newSentence) {
this.sentences.add(newSentence);
}
public final String text() {
return this.text;
}
public final List<Sentence> sentences() {
return Collections.unmodifiableList(this.sentences);
}
/**
* Turn the context into RDF model.
*
* @param tool Tool used to extract the context.
* @param process Process required as RDF model.
* @param host Host from where is hosted the app.
*
* @return RDF model in NIF of the context.
*/ | public final Model rdfModel(final String tool, final NlpProcess process, final String host) { |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context, | 0, 40, 1, NullSentence.getInstance()); |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | final Token token = new TokenImpl("My", "PRP$", 0, 2, NullToken.getInstance(), context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Token.java
// public interface Token {
// void nextToken(final Token newNextToken);
//
// int index();
//
// String text();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullToken.java
// public final class NullToken implements Token {
// static final Logger LOGGER = LoggerFactory.getLogger(NullToken.class);
// private static final NullToken INSTANCE = new NullToken();
//
// public static NullToken getInstance() {
// return NullToken.INSTANCE;
// }
//
// private NullToken() {
// }
//
// @Override
// public void nextToken(final Token newNextToken) {
// throw new UnsupportedOperationException("Not imlpemented");
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public String text() {
// return null;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/TokenImplTest.java
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.interfaces.Token;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullToken;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.ResourceFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class TokenImplTest {
static final Logger LOGGER = LoggerFactory.getLogger(TokenImplTest.class);
public TokenImplTest() {
}
/**
* Test {@link TokenImpl#rdfModel(String, NlpProcess, String)} method of a {@link Token} with a
* next {@link Token}.
*/
@Test
public final void testRdfModelWithNextToken() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62);
final Sentence sentence = new SentenceImpl("My favorite actress is: Natalie Portman.", context,
0, 40, 1, NullSentence.getInstance()); | final Token token = new TokenImpl("My", "PRP$", 0, 2, NullToken.getInstance(), context, |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class ContextTest {
static final Logger LOGGER = LoggerFactory.getLogger(ContextTest.class);
public ContextTest() {
}
/**
* Test {@link Context#rdfModel(String, NlpProcess, String)} method for POS.
*/
@Test
public final void testPosRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class ContextTest {
static final Logger LOGGER = LoggerFactory.getLogger(ContextTest.class);
public ContextTest() {
}
/**
* Test {@link Context#rdfModel(String, NlpProcess, String)} method for POS.
*/
@Test
public final void testPosRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | final Sentence sentence = NullSentence.getInstance(); |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory; | /**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class ContextTest {
static final Logger LOGGER = LoggerFactory.getLogger(ContextTest.class);
public ContextTest() {
}
/**
* Test {@link Context#rdfModel(String, NlpProcess, String)} method for POS.
*/
@Test
public final void testPosRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
/**
* StanfordNLPRESTAPI - Offering a REST API over Stanford CoreNLP to get results in NIF format.
* Copyright © 2017 Julien Plu (julien.plu@redaction-developpez.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.eurecom.stanfordnlprestapi.datatypes;
/**
* @author Julien Plu
*/
public class ContextTest {
static final Logger LOGGER = LoggerFactory.getLogger(ContextTest.class);
public ContextTest() {
}
/**
* Test {@link Context#rdfModel(String, NlpProcess, String)} method for POS.
*/
@Test
public final void testPosRdfModel() {
final Context context = new Context("My favorite actress is: Natalie Portman. She is very "
+ "stunning.", 0, 62); | final Sentence sentence = NullSentence.getInstance(); |
jplu/stanfordNLPRESTAPI | src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
| import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory; | final String nif = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#";
final Map<String, String> prefixes = new HashMap<>();
prefixes.put("nif", nif);
final String base = "http://127.0.0.1/stanfordnlp/context#";
prefixes.put("local", base);
prefixes.put("xsd", "http://www.w3.org/2001/XMLSchema#");
model.setNsPrefixes(prefixes);
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "String"));
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "RFC5147String"));
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "Context"));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "beginIndex"),
ResourceFactory.createTypedLiteral("0", XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "isString"),
ResourceFactory.createTypedLiteral("My favorite actress is: Natalie Portman. She is very "
+ "stunning."));
Assert.assertTrue("Issue to create the model for a Context", | // Path: src/main/java/fr/eurecom/stanfordnlprestapi/enums/NlpProcess.java
// public enum NlpProcess {
// NER,
// POS,
// TOKENIZE,
// COREF,
// DATE,
// NUMBER,
// GAZETTEER
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/interfaces/Sentence.java
// public interface Sentence {
// void addToken(final Token newToken);
//
// void addEntity(final Entity newEntity);
//
// void addCoref(final Coref newCoref);
//
// void nextSentence(final Sentence newNextSentence);
//
// List<Entity> entities();
//
// int index();
//
// int start();
//
// int end();
//
// Model rdfModel(final String tool, final NlpProcess process, final String host);
// }
//
// Path: src/main/java/fr/eurecom/stanfordnlprestapi/nullobjects/NullSentence.java
// public final class NullSentence implements Sentence {
// static final Logger LOGGER = LoggerFactory.getLogger(NullSentence.class);
// private static final NullSentence INSTANCE = new NullSentence();
//
// public static NullSentence getInstance() {
// return NullSentence.INSTANCE;
// }
//
// private NullSentence() {
// }
//
// @Override
// public void addToken(final Token newToken) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addEntity(final Entity newEntity) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void addCoref(final Coref newCoref) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public void nextSentence(final Sentence newNextSentence) {
// throw new UnsupportedOperationException("Not implemented");
// }
//
// @Override
// public List<Entity> entities() {
// return null;
// }
//
// @Override
// public int index() {
// return -1;
// }
//
// @Override
// public int start() {
// return 0;
// }
//
// @Override
// public int end() {
// return 0;
// }
//
// @Override
// public Model rdfModel(final String tool, final NlpProcess process, final String host) {
// return ModelFactory.createDefaultModel();
// }
// }
// Path: src/test/java/fr/eurecom/stanfordnlprestapi/datatypes/ContextTest.java
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.vocabulary.RDF;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.eurecom.stanfordnlprestapi.enums.NlpProcess;
import fr.eurecom.stanfordnlprestapi.interfaces.Sentence;
import fr.eurecom.stanfordnlprestapi.nullobjects.NullSentence;
import java.util.HashMap;
import java.util.Map;
import org.apache.jena.datatypes.xsd.XSDDatatype;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
final String nif = "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#";
final Map<String, String> prefixes = new HashMap<>();
prefixes.put("nif", nif);
final String base = "http://127.0.0.1/stanfordnlp/context#";
prefixes.put("local", base);
prefixes.put("xsd", "http://www.w3.org/2001/XMLSchema#");
model.setNsPrefixes(prefixes);
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "String"));
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "RFC5147String"));
model.add(ResourceFactory.createResource(base + "char=0,62"), RDF.type,
ResourceFactory.createResource(nif + "Context"));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "beginIndex"),
ResourceFactory.createTypedLiteral("0", XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "endIndex"), ResourceFactory.createTypedLiteral("62",
XSDDatatype.XSDnonNegativeInteger));
model.add(ResourceFactory.createResource(base + "char=0,62"),
ResourceFactory.createProperty(nif + "isString"),
ResourceFactory.createTypedLiteral("My favorite actress is: Natalie Portman. She is very "
+ "stunning."));
Assert.assertTrue("Issue to create the model for a Context", | model.isIsomorphicWith(context.rdfModel("stanfordnlp", NlpProcess.POS, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.