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 |
|---|---|---|---|---|---|---|
ParaskP7/sample-code-posts | app/src/test/java/io/petros/posts/datastore/DatastoreAddActionsTest.java | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
| import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.model.User;
import io.realm.Realm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; | package io.petros.posts.datastore;
/**
* This test is ignored until PowerMock is introduced, which will mock all the Realm objects.
*/
@Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction")
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class DatastoreAddActionsTest extends RobolectricGeneralTestHelper {
private DatastoreAddActions datastoreAddActions;
@Mock private Realm realmMock; | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
// Path: app/src/test/java/io/petros/posts/datastore/DatastoreAddActionsTest.java
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.model.User;
import io.realm.Realm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
package io.petros.posts.datastore;
/**
* This test is ignored until PowerMock is introduced, which will mock all the Realm objects.
*/
@Ignore("java.lang.NullPointerException at io.realm.BaseRealm.beginTransaction")
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class DatastoreAddActionsTest extends RobolectricGeneralTestHelper {
private DatastoreAddActions datastoreAddActions;
@Mock private Realm realmMock; | @Mock private User realmUserMock; |
ParaskP7/sample-code-posts | app/src/test/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapterTest.java | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
| import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import java.util.List;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.model.Post;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package io.petros.posts.activity.posts.view.recycler;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostRecyclerViewAdapterTest extends RobolectricGeneralTestHelper {
private static final int POSITION = 0;
private PostRecyclerViewAdapter postRecyclerViewAdapter;
@Mock private OnViewClickListener onViewClickListenerMock;
@Mock private PostViewHolder holderMock; | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
// Path: app/src/test/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapterTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import java.util.List;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.model.Post;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.activity.posts.view.recycler;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostRecyclerViewAdapterTest extends RobolectricGeneralTestHelper {
private static final int POSITION = 0;
private PostRecyclerViewAdapter postRecyclerViewAdapter;
@Mock private OnViewClickListener onViewClickListenerMock;
@Mock private PostViewHolder holderMock; | @Mock private List<Post> postsMock; |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
| import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query; | package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts") | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java
import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts") | Observable<List<Post>> posts(); |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
| import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query; | package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts")
Observable<List<Post>> posts();
@GET("/users") | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java
import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts")
Observable<List<Post>> posts();
@GET("/users") | Observable<List<User>> users(); |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
| import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query; | package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts")
Observable<List<Post>> posts();
@GET("/users")
Observable<List<User>> users();
@GET("/comments") | // Path: app/src/main/java/io/petros/posts/model/Comment.java
// public class Comment {
//
// public static final String POST_ID = "postId";
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String EMAIL = "email";
// public static final String BODY = "body";
//
// @SerializedName(POST_ID)
// @Expose
// private Integer postId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getPostId() {
// return postId;
// }
//
// public void setPostId(final Integer postId) {
// this.postId = postId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/model/User.java
// public class User extends RealmObject {
//
// public static final String ID = "id";
// public static final String NAME = "name";
// public static final String USERNAME = "username";
// public static final String EMAIL = "email";
//
// @SerializedName(ID)
// @Expose
// @PrimaryKey
// private Integer id;
//
// @SerializedName(NAME)
// @Expose
// private String name;
//
// @SerializedName(USERNAME)
// @Expose
// private String username;
//
// @SerializedName(EMAIL)
// @Expose
// private String email;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(final String email) {
// this.email = email;
// }
//
// }
// Path: app/src/main/java/io/petros/posts/service/retrofit/RetrofitService.java
import java.util.List;
import io.petros.posts.model.Comment;
import io.petros.posts.model.Post;
import io.petros.posts.model.User;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
package io.petros.posts.service.retrofit;
public interface RetrofitService {
@GET("/posts")
Observable<List<Post>> posts();
@GET("/users")
Observable<List<User>> users();
@GET("/comments") | Observable<List<Comment>> comments(@Query("postId") int postId); |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/app/graph/modules/ServiceModule.java | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java
// public class InternetAvailabilityDetector implements AvailabilityDetector {
//
// private final ConnectivityManager connectivityManager;
//
// public InternetAvailabilityDetector(final PostsApplication application) {
// this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
// }
//
// @Override
// public boolean isAvailable() {
// @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// if (activeNetworkInfo != null) {
// if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// Timber.v("Internet connection is available; Connected to WiFi.");
// return true;
// } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// Timber.v("Internet connection is available; Connected to the mobile provider's data plan.");
// return true;
// } else {
// Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType());
// return true;
// }
// } else {
// Timber.d("Internet connection is not available at the moment.");
// return false;
// }
// }
//
// }
| import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.service.detector.InternetAvailabilityDetector; | package io.petros.posts.app.graph.modules;
@Module
public class ServiceModule {
@Provides
@Singleton | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java
// public class InternetAvailabilityDetector implements AvailabilityDetector {
//
// private final ConnectivityManager connectivityManager;
//
// public InternetAvailabilityDetector(final PostsApplication application) {
// this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
// }
//
// @Override
// public boolean isAvailable() {
// @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// if (activeNetworkInfo != null) {
// if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// Timber.v("Internet connection is available; Connected to WiFi.");
// return true;
// } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// Timber.v("Internet connection is available; Connected to the mobile provider's data plan.");
// return true;
// } else {
// Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType());
// return true;
// }
// } else {
// Timber.d("Internet connection is not available at the moment.");
// return false;
// }
// }
//
// }
// Path: app/src/main/java/io/petros/posts/app/graph/modules/ServiceModule.java
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.service.detector.InternetAvailabilityDetector;
package io.petros.posts.app.graph.modules;
@Module
public class ServiceModule {
@Provides
@Singleton | InternetAvailabilityDetector provideInternetAvailabilityDetector(final PostsApplication application) { |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/app/graph/modules/ServiceModule.java | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java
// public class InternetAvailabilityDetector implements AvailabilityDetector {
//
// private final ConnectivityManager connectivityManager;
//
// public InternetAvailabilityDetector(final PostsApplication application) {
// this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
// }
//
// @Override
// public boolean isAvailable() {
// @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// if (activeNetworkInfo != null) {
// if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// Timber.v("Internet connection is available; Connected to WiFi.");
// return true;
// } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// Timber.v("Internet connection is available; Connected to the mobile provider's data plan.");
// return true;
// } else {
// Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType());
// return true;
// }
// } else {
// Timber.d("Internet connection is not available at the moment.");
// return false;
// }
// }
//
// }
| import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.service.detector.InternetAvailabilityDetector; | package io.petros.posts.app.graph.modules;
@Module
public class ServiceModule {
@Provides
@Singleton | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/service/detector/InternetAvailabilityDetector.java
// public class InternetAvailabilityDetector implements AvailabilityDetector {
//
// private final ConnectivityManager connectivityManager;
//
// public InternetAvailabilityDetector(final PostsApplication application) {
// this.connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
// }
//
// @Override
// public boolean isAvailable() {
// @Nullable final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
// if (activeNetworkInfo != null) {
// if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// Timber.v("Internet connection is available; Connected to WiFi.");
// return true;
// } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// Timber.v("Internet connection is available; Connected to the mobile provider's data plan.");
// return true;
// } else {
// Timber.v("Internet connection is available. [Network Type: %d]", activeNetworkInfo.getType());
// return true;
// }
// } else {
// Timber.d("Internet connection is not available at the moment.");
// return false;
// }
// }
//
// }
// Path: app/src/main/java/io/petros/posts/app/graph/modules/ServiceModule.java
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.service.detector.InternetAvailabilityDetector;
package io.petros.posts.app.graph.modules;
@Module
public class ServiceModule {
@Provides
@Singleton | InternetAvailabilityDetector provideInternetAvailabilityDetector(final PostsApplication application) { |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/app/actions/AppSnackbarActions.java | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/util/DeprecationUtilities.java
// public final class DeprecationUtilities {
//
// private DeprecationUtilities() {
// throw new AssertionError();
// }
//
// public static void setBackground(final View view, final int drawableId) {
// final Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableId);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// view.setBackground(drawable);
// } else {
// view.setBackgroundDrawable(drawable);
// }
// }
//
// }
| import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import javax.annotation.Nullable;
import io.petros.posts.R;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.util.DeprecationUtilities;
import timber.log.Timber; | public void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout) {
this.coordinatorLayout = coordinatorLayout;
}
// SNACKBAR // **********************************************************************************************************
@SuppressWarnings("checkstyle:whitespacearound")
public void info(final int textResId) {
final String text = application.getString(textResId);
if (coordinatorLayout != null) {
final Snackbar snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_LONG) // @formatter:off
.setAction(defaultActionText, v -> {}); // @formatter:on
setColors(snackbar, 0, R.color.white, R.color.color_accent);
snackbar.show();
} else {
Toast.makeText(application, text, Toast.LENGTH_LONG).show();
}
}
private void setColors(final Snackbar snackbar, final int backgroundColorId, final int textColorId, final int actionTextColorId) {
changeSnackbarBackgroundColor(snackbar, backgroundColorId);
changeSnackbarTextColor(snackbar, textColorId);
changeSnackbarActionTextColor(snackbar, actionTextColorId);
}
private void changeSnackbarBackgroundColor(final Snackbar snackbar, final int backgroundColorId) {
final View snackbarView = snackbar.getView();
if (backgroundColorId != 0) {
snackbarView.setBackgroundColor(ContextCompat.getColor(application, backgroundColorId));
} else { // This is the snackbar's default background color. | // Path: app/src/main/java/io/petros/posts/app/PostsApplication.java
// @SuppressWarnings("checkstyle:overloadmethodsdeclarationorder")
// public class PostsApplication extends Application {
//
// private static ApplicationComponent applicationComponent;
//
// static {
// AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); // NOTE: This enables the "proxy" trick on the vector images.
// }
//
// @Inject AppSnackbarActions appSnackbarActions;
//
// // HELPER // ************************************************************************************************************
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public static SnackbarActions snackbar(final Activity activity) {
// return ((PostsApplication) activity.getApplication()).snackbar();
// }
//
// // APPLICATION // *******************************************************************************************************
//
// @Override
// public void onCreate() {
// super.onCreate();
// initDagger();
// initRealm();
// initTimber();
// Timber.i("Posts application created!");
// }
//
// private void initDagger() {
// applicationComponent = DaggerApplicationComponent.builder()
// .appModule(new AppModule(this))
// .netModule(new NetModule(BASE_URL))
// .dataModule(new DataModule())
// .serviceModule(new ServiceModule())
// .activityModule(new ActivityModule()).build();
// applicationComponent.inject(this);
// }
//
// private void initTimber() {
// Timber.plant(new Timber.DebugTree());
// }
//
// protected void initRealm() {
// Realm.init(this);
// }
//
// // GET // ***************************************************************************************************************
//
// public Realm getDefaultRealmInstance() {
// return Realm.getDefaultInstance();
// }
//
// // ACTIONS // ***********************************************************************************************************
//
// public SnackbarActions snackbar() {
// return appSnackbarActions;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/util/DeprecationUtilities.java
// public final class DeprecationUtilities {
//
// private DeprecationUtilities() {
// throw new AssertionError();
// }
//
// public static void setBackground(final View view, final int drawableId) {
// final Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableId);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// view.setBackground(drawable);
// } else {
// view.setBackgroundDrawable(drawable);
// }
// }
//
// }
// Path: app/src/main/java/io/petros/posts/app/actions/AppSnackbarActions.java
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import javax.annotation.Nullable;
import io.petros.posts.R;
import io.petros.posts.app.PostsApplication;
import io.petros.posts.util.DeprecationUtilities;
import timber.log.Timber;
public void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout) {
this.coordinatorLayout = coordinatorLayout;
}
// SNACKBAR // **********************************************************************************************************
@SuppressWarnings("checkstyle:whitespacearound")
public void info(final int textResId) {
final String text = application.getString(textResId);
if (coordinatorLayout != null) {
final Snackbar snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_LONG) // @formatter:off
.setAction(defaultActionText, v -> {}); // @formatter:on
setColors(snackbar, 0, R.color.white, R.color.color_accent);
snackbar.show();
} else {
Toast.makeText(application, text, Toast.LENGTH_LONG).show();
}
}
private void setColors(final Snackbar snackbar, final int backgroundColorId, final int textColorId, final int actionTextColorId) {
changeSnackbarBackgroundColor(snackbar, backgroundColorId);
changeSnackbarTextColor(snackbar, textColorId);
changeSnackbarActionTextColor(snackbar, actionTextColorId);
}
private void changeSnackbarBackgroundColor(final Snackbar snackbar, final int backgroundColorId) {
final View snackbarView = snackbar.getView();
if (backgroundColorId != 0) {
snackbarView.setBackgroundColor(ContextCompat.getColor(application, backgroundColorId));
} else { // This is the snackbar's default background color. | DeprecationUtilities.setBackground(snackbarView, R.drawable.snackbar__design_snackbar_background); |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java | // Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
| import android.support.annotation.VisibleForTesting;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import io.petros.posts.R;
import io.petros.posts.model.Post;
import timber.log.Timber; | package io.petros.posts.activity.posts.view.recycler;
public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter {
private final OnViewClickListener onViewClickListener;
| // Path: app/src/main/java/io/petros/posts/model/Post.java
// public class Post {
//
// public static final String USER_ID = "userId";
// public static final String ID = "id";
// public static final String TITLE = "title";
// public static final String BODY = "body";
//
// @SerializedName(USER_ID)
// @Expose
// private Integer userId;
//
// @SerializedName(ID)
// @Expose
// private Integer id;
//
// @SerializedName(TITLE)
// @Expose
// private String title;
//
// @SerializedName(BODY)
// @Expose
// private String body;
//
// public Integer getUserId() {
// return userId;
// }
//
// public void setUserId(final Integer userId) {
// this.userId = userId;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(final String title) {
// this.title = title;
// }
//
// public String getBody() {
// return body;
// }
//
// public void setBody(final String body) {
// this.body = body;
// }
//
// }
// Path: app/src/main/java/io/petros/posts/activity/posts/view/recycler/PostRecyclerViewAdapter.java
import android.support.annotation.VisibleForTesting;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import io.petros.posts.R;
import io.petros.posts.model.Post;
import timber.log.Timber;
package io.petros.posts.activity.posts.view.recycler;
public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostViewHolder> implements RecyclerViewAdapter {
private final OnViewClickListener onViewClickListener;
| @VisibleForTesting List<Post> allPosts; |
ParaskP7/sample-code-posts | app/src/test/java/io/petros/posts/app/PostsApplicationTest.java | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java
// public interface SnackbarActions {
//
// void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout);
//
// void info(final int textResId);
//
// void warn(final int textResId);
//
// void error(final int textResId);
//
// }
| import android.app.Activity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.app.actions.SnackbarActions;
import io.realm.Realm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when; | package io.petros.posts.app;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostsApplicationTest extends RobolectricGeneralTestHelper {
@Mock private Activity activityMock;
@Before
public void setUp() {
setUpMocks();
setUpApplication();
}
private void setUpApplication() {
when(activityMock.getApplication()).thenReturn(application);
}
// HELPER // ************************************************************************************************************
@Test
public void snackbarTestFromActivity() { | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/main/java/io/petros/posts/app/actions/SnackbarActions.java
// public interface SnackbarActions {
//
// void setCoordinatorLayout(final CoordinatorLayout coordinatorLayout);
//
// void info(final int textResId);
//
// void warn(final int textResId);
//
// void error(final int textResId);
//
// }
// Path: app/src/test/java/io/petros/posts/app/PostsApplicationTest.java
import android.app.Activity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import io.petros.posts.app.actions.SnackbarActions;
import io.realm.Realm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
package io.petros.posts.app;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class PostsApplicationTest extends RobolectricGeneralTestHelper {
@Mock private Activity activityMock;
@Before
public void setUp() {
setUpMocks();
setUpApplication();
}
private void setUpApplication() {
when(activityMock.getApplication()).thenReturn(application);
}
// HELPER // ************************************************************************************************************
@Test
public void snackbarTestFromActivity() { | final SnackbarActions snackbarActions = PostsApplication.snackbar(activityMock); |
ParaskP7/sample-code-posts | app/src/main/java/io/petros/posts/util/AvatarUtilities.java | // Path: app/src/main/java/io/petros/posts/util/GeneralUtilities.java
// public static final String SLASH = "/";
| import static io.petros.posts.util.GeneralUtilities.SLASH; | package io.petros.posts.util;
public final class AvatarUtilities {
private static final String PROFILE_PIC_URL_PREFIX = "https://api.adorable.io/avatars";
private static final int PROFILE_PIC_SIZE = 150;
private static final String PROFILE_PIC_URL_SUFFIX = ".png";
private AvatarUtilities() {
throw new AssertionError();
}
public static String getUri(final String email) { | // Path: app/src/main/java/io/petros/posts/util/GeneralUtilities.java
// public static final String SLASH = "/";
// Path: app/src/main/java/io/petros/posts/util/AvatarUtilities.java
import static io.petros.posts.util.GeneralUtilities.SLASH;
package io.petros.posts.util;
public final class AvatarUtilities {
private static final String PROFILE_PIC_URL_PREFIX = "https://api.adorable.io/avatars";
private static final int PROFILE_PIC_SIZE = 150;
private static final String PROFILE_PIC_URL_SUFFIX = ".png";
private AvatarUtilities() {
throw new AssertionError();
}
public static String getUri(final String email) { | return PROFILE_PIC_URL_PREFIX + SLASH + PROFILE_PIC_SIZE + SLASH + email + PROFILE_PIC_URL_SUFFIX; |
ParaskP7/sample-code-posts | app/src/test/java/io/petros/posts/util/VersionUtilitiesTest.java | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/util/WhiteboxTestUtilities.java
// public static final String SDK_INT = "SDK_INT";
| import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.util.ReflectionHelpers;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import static io.petros.posts.util.WhiteboxTestUtilities.SDK_INT;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package io.petros.posts.util;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class VersionUtilitiesTest extends RobolectricGeneralTestHelper {
@Mock private Activity activityMock;
@Mock private Intent intentMock;
@Mock private Bundle optionsMock;
@Before
public void setUp() {
setUpMocks();
}
@Test
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void startActivityTestForJellyBeanAndAfter() {
VersionUtilities.startActivity(activityMock, intentMock, optionsMock);
verify(activityMock, times(1)).startActivity(intentMock, optionsMock);
verifyNoMoreInteractions(activityMock);
}
@Test
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public void startActivityTestForPriorJellyBean() { | // Path: app/src/test/java/io/petros/posts/PreconfiguredRobolectricTestRunner.java
// public class PreconfiguredRobolectricTestRunner extends RobolectricTestRunner {
//
// private static final int SDK_API_LEVEL_TO_EMULATE = 25;
//
// /**
// * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file and res directory by
// * default. Use the {@link Config} annotation to configure.
// *
// * @param testClass The test class to be run.
// * @throws InitializationError If junit says so.
// */
// public PreconfiguredRobolectricTestRunner(final Class<?> testClass) throws InitializationError {
// super(testClass);
// }
//
// @Override
// protected Config buildGlobalConfig() {
// return new Config.Builder()
// .setSdk(SDK_API_LEVEL_TO_EMULATE)
// .setManifest(Config.NONE)
// .setApplication(TestPostsApplication.class)
// .build();
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/RobolectricGeneralTestHelper.java
// public class RobolectricGeneralTestHelper extends GeneralTestHelper {
//
// // Application specific fields.
// protected final Context context = getTestContext();
// protected final PostsApplication application = getTestApplication();
//
// // System specific fields.
// @Mock protected ConnectivityManager connectivityManagerMock;
//
// // Activity specific fields.
// @Mock protected PostsApplication applicationMock;
// @Mock protected SnackbarActions snackbarActionsMock;
//
// // ROBOLECTRIC // *******************************************************************************************************
//
// private Context getTestContext() {
// return getShadowApplication().getApplicationContext();
// }
//
// private ShadowApplication getShadowApplication() {
// return ShadowApplication.getInstance();
// }
//
// private PostsApplication getTestApplication() {
// return (PostsApplication) RuntimeEnvironment.application;
// }
//
// // MOCKS // *************************************************************************************************************
//
// protected void setUpMocks() {
// super.setUpMocks();
// setUpApplicationMocks();
// }
//
// private void setUpApplicationMocks() {
// when(applicationMock.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManagerMock);
// when(applicationMock.snackbar()).thenReturn(snackbarActionsMock);
// }
//
// // POST // **************************************************************************************************************
//
// protected Bundle getExtras(final Post post) {
// final Bundle extras = new Bundle();
// extras.putInt(Post.USER_ID, post.getUserId());
// extras.putInt(Post.ID, post.getId());
// extras.putString(Post.TITLE, post.getTitle());
// extras.putString(Post.BODY, post.getBody());
// return extras;
// }
//
// }
//
// Path: app/src/test/java/io/petros/posts/util/WhiteboxTestUtilities.java
// public static final String SDK_INT = "SDK_INT";
// Path: app/src/test/java/io/petros/posts/util/VersionUtilitiesTest.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.util.ReflectionHelpers;
import io.petros.posts.PreconfiguredRobolectricTestRunner;
import io.petros.posts.RobolectricGeneralTestHelper;
import static io.petros.posts.util.WhiteboxTestUtilities.SDK_INT;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package io.petros.posts.util;
@RunWith(PreconfiguredRobolectricTestRunner.class)
public class VersionUtilitiesTest extends RobolectricGeneralTestHelper {
@Mock private Activity activityMock;
@Mock private Intent intentMock;
@Mock private Bundle optionsMock;
@Before
public void setUp() {
setUpMocks();
}
@Test
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void startActivityTestForJellyBeanAndAfter() {
VersionUtilities.startActivity(activityMock, intentMock, optionsMock);
verify(activityMock, times(1)).startActivity(intentMock, optionsMock);
verifyNoMoreInteractions(activityMock);
}
@Test
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public void startActivityTestForPriorJellyBean() { | ReflectionHelpers.setStaticField(Build.VERSION.class, SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1); |
ryanluker/vscode-coverage-gutters | example/java/my-app/src/test/java/com/mycompany/app/AppTest.java | // Path: example/java/my-app/src/main/java/com/mycompany/app/App.java
// public class App
// {
// public static void main( String[] args )
// {
// System.out.println( "Hello World!" );
// }
//
// public static int addTwoOnlyIfEven( int value )
// {
// int remainder = value % 2;
// if (remainder == 0)
// {
// return value + 2;
// }
// return value;
// }
// }
| import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.mycompany.app.App; | package com.mycompany.app;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
public void testAddTwoHappyFlow()
{ | // Path: example/java/my-app/src/main/java/com/mycompany/app/App.java
// public class App
// {
// public static void main( String[] args )
// {
// System.out.println( "Hello World!" );
// }
//
// public static int addTwoOnlyIfEven( int value )
// {
// int remainder = value % 2;
// if (remainder == 0)
// {
// return value + 2;
// }
// return value;
// }
// }
// Path: example/java/my-app/src/test/java/com/mycompany/app/AppTest.java
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.mycompany.app.App;
package com.mycompany.app;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
public void testAddTwoHappyFlow()
{ | int value = App.addTwoOnlyIfEven( 2 ); |
slide-lig/jlcm | src/main/java/fr/liglab/jlcm/internals/Counters.java | // Path: src/main/java/fr/liglab/jlcm/util/ItemAndSupport.java
// public class ItemAndSupport implements Comparable<ItemAndSupport> {
//
// public int item;
// public int support;
//
// public ItemAndSupport(int i, int s) {
// this.item = i;
// this.support = s;
// }
//
// /**
// * Returns a negative integer, zero, or a positive integer
// * as this object's support is less than, equal to, or
// * greater than the specified object's support.
// */
// public int compareTo(ItemAndSupport other) {
// if (other.support == this.support) {
// return this.item - other.item;
// } else {
// return other.support - this.support;
// }
// }
//
// }
//
// Path: src/main/java/fr/liglab/jlcm/util/ItemsetsFactory.java
// public class ItemsetsFactory {
//
// // default constructor FTW
//
// protected TIntArrayList buffer = new TIntArrayList();
// protected int capacity = 50;
//
// /**
// * If you're going big
// * @param c an estimation of future array's size
// */
// public void ensureCapacity(final int c) {
// buffer.ensureCapacity(c);
// }
//
// public void add(final int i) {
// buffer.add(i);
// }
//
// /**
// * Resets the builder by the way
// * @return an array containing latest items added.
// */
// public int[] get() {
// if (capacity < buffer.size()) {
// capacity = buffer.size();
// }
// int[] res = buffer.toArray();
// buffer.clear(capacity);
// return res;
// }
//
// public boolean isEmpty() {
// return buffer.isEmpty();
// }
//
// /////////////////////////////////////////////////////////////////////////
//
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] pattern, final int extension, final int[] closure) {
// if (closure == null) {
// return extend(pattern, extension);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments with their contents renamed EXCEPT for 'pattern' !
// */
// public static int[] extendRename(final int[] closure, final int extension, final int[] pattern,
// final int[] renaming) {
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// for (int i = 0; i < closure.length; i++) {
// extended[i] = renaming[closure[i]];
// }
//
// extended[closure.length] = renaming[extension];
// System.arraycopy(pattern, 0, extended, closure.length + 1, pattern.length);
//
// return extended;
// }
//
// public static int[] extend(final int[] pattern, final int extension, final int[] closure, final int[] ignoreItems) {
// if (ignoreItems == null) {
// return extend(pattern, extension, closure);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1 + ignoreItems.length];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
// System.arraycopy(ignoreItems, 0, extended, pattern.length + 1 + closure.length, ignoreItems.length);
// System.arraycopy(closure, 0, extended, pattern.length+1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] closure, final int extension) {
// int[] extended = new int[closure.length + 1];
//
// System.arraycopy(closure, 0, extended, 0, closure.length);
// extended[closure.length] = extension;
//
// return extended;
// }
// }
| import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicInteger;
import fr.liglab.jlcm.util.ItemAndSupport;
import fr.liglab.jlcm.util.ItemsetsFactory;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.hash.TIntIntHashMap; | TransactionReader transaction = transactions.next();
int weight = transaction.getTransactionSupport();
if (weight > 0) {
if (transaction.hasNext()) {
weightsSum += weight;
transactionsCount++;
}
while (transaction.hasNext()) {
int item = transaction.next();
if (item <= maxItem) {
this.supportCounts[item] += weight;
this.distinctTransactionsCounts[item]++;
}
}
}
}
this.transactionsCount = weightsSum;
this.distinctTransactionsCount = transactionsCount;
// ignored items
this.supportCounts[extension] = 0;
this.distinctTransactionsCounts[extension] = 0;
this.maxCandidate = extension;
// item filtering and final computations : some are infrequent, some
// belong to closure
| // Path: src/main/java/fr/liglab/jlcm/util/ItemAndSupport.java
// public class ItemAndSupport implements Comparable<ItemAndSupport> {
//
// public int item;
// public int support;
//
// public ItemAndSupport(int i, int s) {
// this.item = i;
// this.support = s;
// }
//
// /**
// * Returns a negative integer, zero, or a positive integer
// * as this object's support is less than, equal to, or
// * greater than the specified object's support.
// */
// public int compareTo(ItemAndSupport other) {
// if (other.support == this.support) {
// return this.item - other.item;
// } else {
// return other.support - this.support;
// }
// }
//
// }
//
// Path: src/main/java/fr/liglab/jlcm/util/ItemsetsFactory.java
// public class ItemsetsFactory {
//
// // default constructor FTW
//
// protected TIntArrayList buffer = new TIntArrayList();
// protected int capacity = 50;
//
// /**
// * If you're going big
// * @param c an estimation of future array's size
// */
// public void ensureCapacity(final int c) {
// buffer.ensureCapacity(c);
// }
//
// public void add(final int i) {
// buffer.add(i);
// }
//
// /**
// * Resets the builder by the way
// * @return an array containing latest items added.
// */
// public int[] get() {
// if (capacity < buffer.size()) {
// capacity = buffer.size();
// }
// int[] res = buffer.toArray();
// buffer.clear(capacity);
// return res;
// }
//
// public boolean isEmpty() {
// return buffer.isEmpty();
// }
//
// /////////////////////////////////////////////////////////////////////////
//
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] pattern, final int extension, final int[] closure) {
// if (closure == null) {
// return extend(pattern, extension);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments with their contents renamed EXCEPT for 'pattern' !
// */
// public static int[] extendRename(final int[] closure, final int extension, final int[] pattern,
// final int[] renaming) {
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// for (int i = 0; i < closure.length; i++) {
// extended[i] = renaming[closure[i]];
// }
//
// extended[closure.length] = renaming[extension];
// System.arraycopy(pattern, 0, extended, closure.length + 1, pattern.length);
//
// return extended;
// }
//
// public static int[] extend(final int[] pattern, final int extension, final int[] closure, final int[] ignoreItems) {
// if (ignoreItems == null) {
// return extend(pattern, extension, closure);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1 + ignoreItems.length];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
// System.arraycopy(ignoreItems, 0, extended, pattern.length + 1 + closure.length, ignoreItems.length);
// System.arraycopy(closure, 0, extended, pattern.length+1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] closure, final int extension) {
// int[] extended = new int[closure.length + 1];
//
// System.arraycopy(closure, 0, extended, 0, closure.length);
// extended[closure.length] = extension;
//
// return extended;
// }
// }
// Path: src/main/java/fr/liglab/jlcm/internals/Counters.java
import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicInteger;
import fr.liglab.jlcm.util.ItemAndSupport;
import fr.liglab.jlcm.util.ItemsetsFactory;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.hash.TIntIntHashMap;
TransactionReader transaction = transactions.next();
int weight = transaction.getTransactionSupport();
if (weight > 0) {
if (transaction.hasNext()) {
weightsSum += weight;
transactionsCount++;
}
while (transaction.hasNext()) {
int item = transaction.next();
if (item <= maxItem) {
this.supportCounts[item] += weight;
this.distinctTransactionsCounts[item]++;
}
}
}
}
this.transactionsCount = weightsSum;
this.distinctTransactionsCount = transactionsCount;
// ignored items
this.supportCounts[extension] = 0;
this.distinctTransactionsCounts[extension] = 0;
this.maxCandidate = extension;
// item filtering and final computations : some are infrequent, some
// belong to closure
| ItemsetsFactory closureBuilder = new ItemsetsFactory(); |
slide-lig/jlcm | src/main/java/fr/liglab/jlcm/internals/Counters.java | // Path: src/main/java/fr/liglab/jlcm/util/ItemAndSupport.java
// public class ItemAndSupport implements Comparable<ItemAndSupport> {
//
// public int item;
// public int support;
//
// public ItemAndSupport(int i, int s) {
// this.item = i;
// this.support = s;
// }
//
// /**
// * Returns a negative integer, zero, or a positive integer
// * as this object's support is less than, equal to, or
// * greater than the specified object's support.
// */
// public int compareTo(ItemAndSupport other) {
// if (other.support == this.support) {
// return this.item - other.item;
// } else {
// return other.support - this.support;
// }
// }
//
// }
//
// Path: src/main/java/fr/liglab/jlcm/util/ItemsetsFactory.java
// public class ItemsetsFactory {
//
// // default constructor FTW
//
// protected TIntArrayList buffer = new TIntArrayList();
// protected int capacity = 50;
//
// /**
// * If you're going big
// * @param c an estimation of future array's size
// */
// public void ensureCapacity(final int c) {
// buffer.ensureCapacity(c);
// }
//
// public void add(final int i) {
// buffer.add(i);
// }
//
// /**
// * Resets the builder by the way
// * @return an array containing latest items added.
// */
// public int[] get() {
// if (capacity < buffer.size()) {
// capacity = buffer.size();
// }
// int[] res = buffer.toArray();
// buffer.clear(capacity);
// return res;
// }
//
// public boolean isEmpty() {
// return buffer.isEmpty();
// }
//
// /////////////////////////////////////////////////////////////////////////
//
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] pattern, final int extension, final int[] closure) {
// if (closure == null) {
// return extend(pattern, extension);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments with their contents renamed EXCEPT for 'pattern' !
// */
// public static int[] extendRename(final int[] closure, final int extension, final int[] pattern,
// final int[] renaming) {
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// for (int i = 0; i < closure.length; i++) {
// extended[i] = renaming[closure[i]];
// }
//
// extended[closure.length] = renaming[extension];
// System.arraycopy(pattern, 0, extended, closure.length + 1, pattern.length);
//
// return extended;
// }
//
// public static int[] extend(final int[] pattern, final int extension, final int[] closure, final int[] ignoreItems) {
// if (ignoreItems == null) {
// return extend(pattern, extension, closure);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1 + ignoreItems.length];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
// System.arraycopy(ignoreItems, 0, extended, pattern.length + 1 + closure.length, ignoreItems.length);
// System.arraycopy(closure, 0, extended, pattern.length+1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] closure, final int extension) {
// int[] extended = new int[closure.length + 1];
//
// System.arraycopy(closure, 0, extended, 0, closure.length);
// extended[closure.length] = extension;
//
// return extended;
// }
// }
| import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicInteger;
import fr.liglab.jlcm.util.ItemAndSupport;
import fr.liglab.jlcm.util.ItemsetsFactory;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.hash.TIntIntHashMap; | TransactionReader transaction = transactions.next();
int weight = transaction.getTransactionSupport();
if (weight > 0) {
transactionsCounter++;
weightsSum += weight;
while (transaction.hasNext()) {
int item = transaction.next();
biggestItemID = Math.max(biggestItemID, item);
supportsMap.adjustOrPutValue(item, weight, weight);
distinctsTMap.adjustOrPutValue(item, 1, 1);
}
}
}
this.transactionsCount = weightsSum;
this.distinctTransactionsCount = transactionsCounter;
this.renaming = new int[biggestItemID + 1];
Arrays.fill(this.renaming, -1);
if (minimumSupport.isInt()) {
this.minSupport = minimumSupport.getInt();
} else {
this.minSupport = (int) (this.transactionsCount * minimumSupport.getDouble());
}
// item filtering and final computations : some are infrequent, some
// belong to closure
| // Path: src/main/java/fr/liglab/jlcm/util/ItemAndSupport.java
// public class ItemAndSupport implements Comparable<ItemAndSupport> {
//
// public int item;
// public int support;
//
// public ItemAndSupport(int i, int s) {
// this.item = i;
// this.support = s;
// }
//
// /**
// * Returns a negative integer, zero, or a positive integer
// * as this object's support is less than, equal to, or
// * greater than the specified object's support.
// */
// public int compareTo(ItemAndSupport other) {
// if (other.support == this.support) {
// return this.item - other.item;
// } else {
// return other.support - this.support;
// }
// }
//
// }
//
// Path: src/main/java/fr/liglab/jlcm/util/ItemsetsFactory.java
// public class ItemsetsFactory {
//
// // default constructor FTW
//
// protected TIntArrayList buffer = new TIntArrayList();
// protected int capacity = 50;
//
// /**
// * If you're going big
// * @param c an estimation of future array's size
// */
// public void ensureCapacity(final int c) {
// buffer.ensureCapacity(c);
// }
//
// public void add(final int i) {
// buffer.add(i);
// }
//
// /**
// * Resets the builder by the way
// * @return an array containing latest items added.
// */
// public int[] get() {
// if (capacity < buffer.size()) {
// capacity = buffer.size();
// }
// int[] res = buffer.toArray();
// buffer.clear(capacity);
// return res;
// }
//
// public boolean isEmpty() {
// return buffer.isEmpty();
// }
//
// /////////////////////////////////////////////////////////////////////////
//
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] pattern, final int extension, final int[] closure) {
// if (closure == null) {
// return extend(pattern, extension);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments with their contents renamed EXCEPT for 'pattern' !
// */
// public static int[] extendRename(final int[] closure, final int extension, final int[] pattern,
// final int[] renaming) {
//
// int[] extended = new int[pattern.length + closure.length + 1];
//
// for (int i = 0; i < closure.length; i++) {
// extended[i] = renaming[closure[i]];
// }
//
// extended[closure.length] = renaming[extension];
// System.arraycopy(pattern, 0, extended, closure.length + 1, pattern.length);
//
// return extended;
// }
//
// public static int[] extend(final int[] pattern, final int extension, final int[] closure, final int[] ignoreItems) {
// if (ignoreItems == null) {
// return extend(pattern, extension, closure);
// }
//
// int[] extended = new int[pattern.length + closure.length + 1 + ignoreItems.length];
//
// System.arraycopy(pattern, 0, extended, 0, pattern.length);
// extended[pattern.length] = extension;
// System.arraycopy(closure, 0, extended, pattern.length + 1, closure.length);
// System.arraycopy(ignoreItems, 0, extended, pattern.length + 1 + closure.length, ignoreItems.length);
// System.arraycopy(closure, 0, extended, pattern.length+1, closure.length);
//
// return extended;
// }
//
// /**
// * @return a new array concatenating each of its arguments
// */
// public static int[] extend(final int[] closure, final int extension) {
// int[] extended = new int[closure.length + 1];
//
// System.arraycopy(closure, 0, extended, 0, closure.length);
// extended[closure.length] = extension;
//
// return extended;
// }
// }
// Path: src/main/java/fr/liglab/jlcm/internals/Counters.java
import java.util.Arrays;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.concurrent.atomic.AtomicInteger;
import fr.liglab.jlcm.util.ItemAndSupport;
import fr.liglab.jlcm.util.ItemsetsFactory;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.hash.TIntIntHashMap;
TransactionReader transaction = transactions.next();
int weight = transaction.getTransactionSupport();
if (weight > 0) {
transactionsCounter++;
weightsSum += weight;
while (transaction.hasNext()) {
int item = transaction.next();
biggestItemID = Math.max(biggestItemID, item);
supportsMap.adjustOrPutValue(item, weight, weight);
distinctsTMap.adjustOrPutValue(item, 1, 1);
}
}
}
this.transactionsCount = weightsSum;
this.distinctTransactionsCount = transactionsCounter;
this.renaming = new int[biggestItemID + 1];
Arrays.fill(this.renaming, -1);
if (minimumSupport.isInt()) {
this.minSupport = minimumSupport.getInt();
} else {
this.minSupport = (int) (this.transactionsCount * minimumSupport.getDouble());
}
// item filtering and final computations : some are infrequent, some
// belong to closure
| final PriorityQueue<ItemAndSupport> renamingHeap = new PriorityQueue<ItemAndSupport>(); |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/comparison/NumberOfSubmissionsStrategy.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption; | package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom based on the number of times it is suggested by the anntated lattice
*
* @author Pierre Monnin
*
*/
public class NumberOfSubmissionsStrategy extends EvaluationStrategy{
@Override
public String getName() {
return "NumberOfSubmissions";
}
@Override | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/NumberOfSubmissionsStrategy.java
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom based on the number of times it is suggested by the anntated lattice
*
* @author Pierre Monnin
*
*/
public class NumberOfSubmissionsStrategy extends EvaluationStrategy{
@Override
public String getName() {
return "NumberOfSubmissions";
}
@Override | protected double computeValue(DataBasedSubsumption subsumption) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/comparison/AverageExtentRatioStrategy.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.List; | package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom suggested by the annotated lattice computing the average extent ratio
*
* @author Pierre Monnin
*
*/
public class AverageExtentRatioStrategy extends EvaluationStrategy {
@Override
public String getName() {
return "AverageExtensionsRatio";
}
@Override | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/AverageExtentRatioStrategy.java
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.List;
package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom suggested by the annotated lattice computing the average extent ratio
*
* @author Pierre Monnin
*
*/
public class AverageExtentRatioStrategy extends EvaluationStrategy {
@Override
public String getName() {
return "AverageExtensionsRatio";
}
@Override | protected double computeValue(DataBasedSubsumption subsumption) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/factory/DataSetFactory.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlRecord.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlRecord {
// private HashMap<String, SparqlValue> fields = new HashMap<>();
//
// public HashMap<String, SparqlValue> getFields() {
// return this.fields;
// }
//
// @JsonAnySetter
// public void set(String name, SparqlValue value) {
// this.fields.put(name, value);
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlResponse.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlResponse {
// private SparqlHead head;
// private SparqlResults results;
//
// public SparqlHead getHead() {
// return this.head;
// }
//
// public void setHead(SparqlHead head) {
// this.head = head;
// }
//
// public SparqlResults getResults() {
// return this.results;
// }
//
// public void setResults(SparqlResults results) {
// this.results = results;
// }
//
// public ArrayList<SparqlRecord> getRecords() {
// if(this.results != null && this.results.getBindings() != null) {
// return this.results.getBindings();
// }
//
// return new ArrayList<>();
// }
// }
| import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.io.ServerQuerier;
import dbpediaanalyzer.io.SparqlRecord;
import dbpediaanalyzer.io.SparqlResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; | package dbpediaanalyzer.factory;
/**
* Built the data set from DBpedia pages selected with min and max death date
*
* @author Pierre Monnin
*
*/
public class DataSetFactory {
public static Map<String, Page> createDataSet(String minDeathDate, String maxDeathDate, HierarchiesManager hierarchiesManager) {
HashMap<String, Page> dataSet = new HashMap<>();
HashMap<String, Boolean> missingCategories = new HashMap<>();
HashMap<String, Boolean> missingOntologyClasses = new HashMap<>();
HashMap<String, Boolean> missingYagoClasses = new HashMap<>();
try { | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlRecord.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlRecord {
// private HashMap<String, SparqlValue> fields = new HashMap<>();
//
// public HashMap<String, SparqlValue> getFields() {
// return this.fields;
// }
//
// @JsonAnySetter
// public void set(String name, SparqlValue value) {
// this.fields.put(name, value);
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlResponse.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlResponse {
// private SparqlHead head;
// private SparqlResults results;
//
// public SparqlHead getHead() {
// return this.head;
// }
//
// public void setHead(SparqlHead head) {
// this.head = head;
// }
//
// public SparqlResults getResults() {
// return this.results;
// }
//
// public void setResults(SparqlResults results) {
// this.results = results;
// }
//
// public ArrayList<SparqlRecord> getRecords() {
// if(this.results != null && this.results.getBindings() != null) {
// return this.results.getBindings();
// }
//
// return new ArrayList<>();
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/DataSetFactory.java
import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.io.ServerQuerier;
import dbpediaanalyzer.io.SparqlRecord;
import dbpediaanalyzer.io.SparqlResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
package dbpediaanalyzer.factory;
/**
* Built the data set from DBpedia pages selected with min and max death date
*
* @author Pierre Monnin
*
*/
public class DataSetFactory {
public static Map<String, Page> createDataSet(String minDeathDate, String maxDeathDate, HierarchiesManager hierarchiesManager) {
HashMap<String, Page> dataSet = new HashMap<>();
HashMap<String, Boolean> missingCategories = new HashMap<>();
HashMap<String, Boolean> missingOntologyClasses = new HashMap<>();
HashMap<String, Boolean> missingYagoClasses = new HashMap<>();
try { | SparqlResponse response = (new ServerQuerier()).runQuery( |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/factory/DataSetFactory.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlRecord.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlRecord {
// private HashMap<String, SparqlValue> fields = new HashMap<>();
//
// public HashMap<String, SparqlValue> getFields() {
// return this.fields;
// }
//
// @JsonAnySetter
// public void set(String name, SparqlValue value) {
// this.fields.put(name, value);
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlResponse.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlResponse {
// private SparqlHead head;
// private SparqlResults results;
//
// public SparqlHead getHead() {
// return this.head;
// }
//
// public void setHead(SparqlHead head) {
// this.head = head;
// }
//
// public SparqlResults getResults() {
// return this.results;
// }
//
// public void setResults(SparqlResults results) {
// this.results = results;
// }
//
// public ArrayList<SparqlRecord> getRecords() {
// if(this.results != null && this.results.getBindings() != null) {
// return this.results.getBindings();
// }
//
// return new ArrayList<>();
// }
// }
| import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.io.ServerQuerier;
import dbpediaanalyzer.io.SparqlRecord;
import dbpediaanalyzer.io.SparqlResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; | package dbpediaanalyzer.factory;
/**
* Built the data set from DBpedia pages selected with min and max death date
*
* @author Pierre Monnin
*
*/
public class DataSetFactory {
public static Map<String, Page> createDataSet(String minDeathDate, String maxDeathDate, HierarchiesManager hierarchiesManager) {
HashMap<String, Page> dataSet = new HashMap<>();
HashMap<String, Boolean> missingCategories = new HashMap<>();
HashMap<String, Boolean> missingOntologyClasses = new HashMap<>();
HashMap<String, Boolean> missingYagoClasses = new HashMap<>();
try {
SparqlResponse response = (new ServerQuerier()).runQuery(
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX dbo:<http://dbpedia.org/ontology/> " +
"select distinct ?page where { " +
"?page dbo:wikiPageID ?pageId . " +
"?page rdf:type/rdfs:subClassOf* dbo:Person . " +
"?page dbo:deathDate ?deathDate . " +
"FILTER(?deathDate >= \"" + minDeathDate + "\"^^xsd:date) . " +
"FILTER(?deathDate < \"" + maxDeathDate + "\"^^xsd:date) }"
);
| // Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlRecord.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlRecord {
// private HashMap<String, SparqlValue> fields = new HashMap<>();
//
// public HashMap<String, SparqlValue> getFields() {
// return this.fields;
// }
//
// @JsonAnySetter
// public void set(String name, SparqlValue value) {
// this.fields.put(name, value);
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/SparqlResponse.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class SparqlResponse {
// private SparqlHead head;
// private SparqlResults results;
//
// public SparqlHead getHead() {
// return this.head;
// }
//
// public void setHead(SparqlHead head) {
// this.head = head;
// }
//
// public SparqlResults getResults() {
// return this.results;
// }
//
// public void setResults(SparqlResults results) {
// this.results = results;
// }
//
// public ArrayList<SparqlRecord> getRecords() {
// if(this.results != null && this.results.getBindings() != null) {
// return this.results.getBindings();
// }
//
// return new ArrayList<>();
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/DataSetFactory.java
import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.io.ServerQuerier;
import dbpediaanalyzer.io.SparqlRecord;
import dbpediaanalyzer.io.SparqlResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
package dbpediaanalyzer.factory;
/**
* Built the data set from DBpedia pages selected with min and max death date
*
* @author Pierre Monnin
*
*/
public class DataSetFactory {
public static Map<String, Page> createDataSet(String minDeathDate, String maxDeathDate, HierarchiesManager hierarchiesManager) {
HashMap<String, Page> dataSet = new HashMap<>();
HashMap<String, Boolean> missingCategories = new HashMap<>();
HashMap<String, Boolean> missingOntologyClasses = new HashMap<>();
HashMap<String, Boolean> missingYagoClasses = new HashMap<>();
try {
SparqlResponse response = (new ServerQuerier()).runQuery(
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> " +
"PREFIX dbo:<http://dbpedia.org/ontology/> " +
"select distinct ?page where { " +
"?page dbo:wikiPageID ?pageId . " +
"?page rdf:type/rdfs:subClassOf* dbo:Person . " +
"?page dbo:deathDate ?deathDate . " +
"FILTER(?deathDate >= \"" + minDeathDate + "\"^^xsd:date) . " +
"FILTER(?deathDate < \"" + maxDeathDate + "\"^^xsd:date) }"
);
| for(SparqlRecord r : response.getRecords()) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/factory/KnowledgesComparisonResultFactory.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResult.java
// public class ComparisonResult {
// private ComparisonResultType type;
// private HierarchyElement bottom;
// private HierarchyElement top;
// private Map<String, Double> values;
//
// public ComparisonResult(ComparisonResultType type, HierarchyElement bottom, HierarchyElement top) {
// this.type = type;
// this.bottom = bottom;
// this.top = top;
// this.values = new HashMap<>();
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public void addValue(String strategy, double value) {
// this.values.put(strategy, value);
// }
//
// public Map<String, Double> getValues() {
// return new HashMap<>(this.values);
// }
//
// public boolean isInvalid() {
// for(Map.Entry<String, Double> entry : this.values.entrySet()) {
// if(entry.getValue() == EvaluationStrategy.INVALID_RESULT_VALUE) {
// return true;
// }
// }
//
// return false;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResultType.java
// public enum ComparisonResultType {
// CONFIRMED_DIRECT,
// PROPOSED_INFERRED_TO_DIRECT,
// PROPOSED_NEW
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java
// public abstract class EvaluationStrategy {
// public static final double INVALID_RESULT_VALUE = -1.0;
//
// public abstract String getName();
//
// public double evaluateSubsumption(DataBasedSubsumption subsumption) {
// if(subsumption.getTop().hasAncestor(subsumption.getBottom())) {
// return INVALID_RESULT_VALUE;
// }
//
// return computeValue(subsumption);
// }
//
// protected abstract double computeValue(DataBasedSubsumption subsumption);
//
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.comparison.ComparisonResult;
import dbpediaanalyzer.comparison.ComparisonResultType;
import dbpediaanalyzer.comparison.EvaluationStrategy;
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.ArrayList;
import java.util.List; | package dbpediaanalyzer.factory;
/**
* Compares the axioms from the annotated lattice with the existing ontologies
*
* @author Pierre Monnin
*
*/
public class KnowledgesComparisonResultFactory {
public static List<ComparisonResult> createKnowledgesComparisonResults(List<DataBasedSubsumption> dataBasedKnowledge) {
List<ComparisonResult> results = new ArrayList<>();
while(!dataBasedKnowledge.isEmpty()) {
DataBasedSubsumption dbs = dataBasedKnowledge.remove(0);
// Is this an already existing direct relationship?
if(dbs.getBottom().getParents().contains(dbs.getTop())) { | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResult.java
// public class ComparisonResult {
// private ComparisonResultType type;
// private HierarchyElement bottom;
// private HierarchyElement top;
// private Map<String, Double> values;
//
// public ComparisonResult(ComparisonResultType type, HierarchyElement bottom, HierarchyElement top) {
// this.type = type;
// this.bottom = bottom;
// this.top = top;
// this.values = new HashMap<>();
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public void addValue(String strategy, double value) {
// this.values.put(strategy, value);
// }
//
// public Map<String, Double> getValues() {
// return new HashMap<>(this.values);
// }
//
// public boolean isInvalid() {
// for(Map.Entry<String, Double> entry : this.values.entrySet()) {
// if(entry.getValue() == EvaluationStrategy.INVALID_RESULT_VALUE) {
// return true;
// }
// }
//
// return false;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResultType.java
// public enum ComparisonResultType {
// CONFIRMED_DIRECT,
// PROPOSED_INFERRED_TO_DIRECT,
// PROPOSED_NEW
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java
// public abstract class EvaluationStrategy {
// public static final double INVALID_RESULT_VALUE = -1.0;
//
// public abstract String getName();
//
// public double evaluateSubsumption(DataBasedSubsumption subsumption) {
// if(subsumption.getTop().hasAncestor(subsumption.getBottom())) {
// return INVALID_RESULT_VALUE;
// }
//
// return computeValue(subsumption);
// }
//
// protected abstract double computeValue(DataBasedSubsumption subsumption);
//
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/KnowledgesComparisonResultFactory.java
import dbpediaanalyzer.comparison.ComparisonResult;
import dbpediaanalyzer.comparison.ComparisonResultType;
import dbpediaanalyzer.comparison.EvaluationStrategy;
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.ArrayList;
import java.util.List;
package dbpediaanalyzer.factory;
/**
* Compares the axioms from the annotated lattice with the existing ontologies
*
* @author Pierre Monnin
*
*/
public class KnowledgesComparisonResultFactory {
public static List<ComparisonResult> createKnowledgesComparisonResults(List<DataBasedSubsumption> dataBasedKnowledge) {
List<ComparisonResult> results = new ArrayList<>();
while(!dataBasedKnowledge.isEmpty()) {
DataBasedSubsumption dbs = dataBasedKnowledge.remove(0);
// Is this an already existing direct relationship?
if(dbs.getBottom().getParents().contains(dbs.getTop())) { | results.add(createComparisonResult(ComparisonResultType.CONFIRMED_DIRECT, dbs)); |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/factory/KnowledgesComparisonResultFactory.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResult.java
// public class ComparisonResult {
// private ComparisonResultType type;
// private HierarchyElement bottom;
// private HierarchyElement top;
// private Map<String, Double> values;
//
// public ComparisonResult(ComparisonResultType type, HierarchyElement bottom, HierarchyElement top) {
// this.type = type;
// this.bottom = bottom;
// this.top = top;
// this.values = new HashMap<>();
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public void addValue(String strategy, double value) {
// this.values.put(strategy, value);
// }
//
// public Map<String, Double> getValues() {
// return new HashMap<>(this.values);
// }
//
// public boolean isInvalid() {
// for(Map.Entry<String, Double> entry : this.values.entrySet()) {
// if(entry.getValue() == EvaluationStrategy.INVALID_RESULT_VALUE) {
// return true;
// }
// }
//
// return false;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResultType.java
// public enum ComparisonResultType {
// CONFIRMED_DIRECT,
// PROPOSED_INFERRED_TO_DIRECT,
// PROPOSED_NEW
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java
// public abstract class EvaluationStrategy {
// public static final double INVALID_RESULT_VALUE = -1.0;
//
// public abstract String getName();
//
// public double evaluateSubsumption(DataBasedSubsumption subsumption) {
// if(subsumption.getTop().hasAncestor(subsumption.getBottom())) {
// return INVALID_RESULT_VALUE;
// }
//
// return computeValue(subsumption);
// }
//
// protected abstract double computeValue(DataBasedSubsumption subsumption);
//
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.comparison.ComparisonResult;
import dbpediaanalyzer.comparison.ComparisonResultType;
import dbpediaanalyzer.comparison.EvaluationStrategy;
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.ArrayList;
import java.util.List; | package dbpediaanalyzer.factory;
/**
* Compares the axioms from the annotated lattice with the existing ontologies
*
* @author Pierre Monnin
*
*/
public class KnowledgesComparisonResultFactory {
public static List<ComparisonResult> createKnowledgesComparisonResults(List<DataBasedSubsumption> dataBasedKnowledge) {
List<ComparisonResult> results = new ArrayList<>();
while(!dataBasedKnowledge.isEmpty()) {
DataBasedSubsumption dbs = dataBasedKnowledge.remove(0);
// Is this an already existing direct relationship?
if(dbs.getBottom().getParents().contains(dbs.getTop())) {
results.add(createComparisonResult(ComparisonResultType.CONFIRMED_DIRECT, dbs));
}
// Is this an already existing inferred relationship?
else if(dbs.getBottom().hasAncestor(dbs.getTop())) {
results.add(createComparisonResult(ComparisonResultType.PROPOSED_INFERRED_TO_DIRECT, dbs));
}
// Is this a new relationship?
else {
results.add(createComparisonResult(ComparisonResultType.PROPOSED_NEW, dbs));
}
}
return results;
}
private static ComparisonResult createComparisonResult(ComparisonResultType type, DataBasedSubsumption dbs) { | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResult.java
// public class ComparisonResult {
// private ComparisonResultType type;
// private HierarchyElement bottom;
// private HierarchyElement top;
// private Map<String, Double> values;
//
// public ComparisonResult(ComparisonResultType type, HierarchyElement bottom, HierarchyElement top) {
// this.type = type;
// this.bottom = bottom;
// this.top = top;
// this.values = new HashMap<>();
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public void addValue(String strategy, double value) {
// this.values.put(strategy, value);
// }
//
// public Map<String, Double> getValues() {
// return new HashMap<>(this.values);
// }
//
// public boolean isInvalid() {
// for(Map.Entry<String, Double> entry : this.values.entrySet()) {
// if(entry.getValue() == EvaluationStrategy.INVALID_RESULT_VALUE) {
// return true;
// }
// }
//
// return false;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/ComparisonResultType.java
// public enum ComparisonResultType {
// CONFIRMED_DIRECT,
// PROPOSED_INFERRED_TO_DIRECT,
// PROPOSED_NEW
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java
// public abstract class EvaluationStrategy {
// public static final double INVALID_RESULT_VALUE = -1.0;
//
// public abstract String getName();
//
// public double evaluateSubsumption(DataBasedSubsumption subsumption) {
// if(subsumption.getTop().hasAncestor(subsumption.getBottom())) {
// return INVALID_RESULT_VALUE;
// }
//
// return computeValue(subsumption);
// }
//
// protected abstract double computeValue(DataBasedSubsumption subsumption);
//
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/KnowledgesComparisonResultFactory.java
import dbpediaanalyzer.comparison.ComparisonResult;
import dbpediaanalyzer.comparison.ComparisonResultType;
import dbpediaanalyzer.comparison.EvaluationStrategy;
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.ArrayList;
import java.util.List;
package dbpediaanalyzer.factory;
/**
* Compares the axioms from the annotated lattice with the existing ontologies
*
* @author Pierre Monnin
*
*/
public class KnowledgesComparisonResultFactory {
public static List<ComparisonResult> createKnowledgesComparisonResults(List<DataBasedSubsumption> dataBasedKnowledge) {
List<ComparisonResult> results = new ArrayList<>();
while(!dataBasedKnowledge.isEmpty()) {
DataBasedSubsumption dbs = dataBasedKnowledge.remove(0);
// Is this an already existing direct relationship?
if(dbs.getBottom().getParents().contains(dbs.getTop())) {
results.add(createComparisonResult(ComparisonResultType.CONFIRMED_DIRECT, dbs));
}
// Is this an already existing inferred relationship?
else if(dbs.getBottom().hasAncestor(dbs.getTop())) {
results.add(createComparisonResult(ComparisonResultType.PROPOSED_INFERRED_TO_DIRECT, dbs));
}
// Is this a new relationship?
else {
results.add(createComparisonResult(ComparisonResultType.PROPOSED_NEW, dbs));
}
}
return results;
}
private static ComparisonResult createComparisonResult(ComparisonResultType type, DataBasedSubsumption dbs) { | List<EvaluationStrategy> strategies = EvaluationStrategiesFactory.getEvaluationStrategies(); |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/comparison/AverageIntentRatioStrategy.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.List; | package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom suggested by the annotated lattice computing the average intent ratio
*
* @author Pierre Monnin
*
*/
public class AverageIntentRatioStrategy extends EvaluationStrategy {
@Override
public String getName() {
return "AverageIntensionsRatio";
}
@Override | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/AverageIntentRatioStrategy.java
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
import java.util.List;
package dbpediaanalyzer.comparison;
/**
* Evaluates an axiom suggested by the annotated lattice computing the average intent ratio
*
* @author Pierre Monnin
*
*/
public class AverageIntentRatioStrategy extends EvaluationStrategy {
@Override
public String getName() {
return "AverageIntensionsRatio";
}
@Override | protected double computeValue(DataBasedSubsumption subsumption) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
| import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*; | package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java
import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*;
package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations | private List<Category> categories; |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
| import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*; | package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations
private List<Category> categories; | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java
import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*;
package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations
private List<Category> categories; | private List<OntologyClass> ontologyClasses; |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
| import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*; | package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations
private List<Category> categories;
private List<OntologyClass> ontologyClasses; | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/Category.java
// public class Category extends HierarchyElement {
// public static final String DBPEDIA_CATEGORY_URI_PREFIX = "http://dbpedia.org/resource/Category";
//
// public Category(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof Category) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof Category) {
// super.addChild(child);
// }
// }
//
// public static List<Category> getAccessibleUpwardCategories(Collection<Category> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<Category> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((Category) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/OntologyClass.java
// public class OntologyClass extends HierarchyElement {
// public static final String DBPEDIA_ONTOLOGY_CLASS_URI_PREFIX = "http://dbpedia.org/ontology";
//
// public OntologyClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof OntologyClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof OntologyClass) {
// super.addChild(child);
// }
// }
//
// public static List<OntologyClass> getAccessibleUpwardOntologyClasses(Collection<OntologyClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<OntologyClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((OntologyClass) he);
// }
//
// return retVal;
// }
// }
//
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/dbpediaobject/YagoClass.java
// public class YagoClass extends HierarchyElement {
// public static final String DBPEDIA_YAGO_CLASS_URI_PREFIX = "http://dbpedia.org/class/yago";
//
// public YagoClass(String uri) {
// super(uri);
// }
//
// @Override
// public void addParent(HierarchyElement parent) {
// if(parent instanceof YagoClass) {
// super.addParent(parent);
// }
// }
//
// @Override
// public void addChild(HierarchyElement child) {
// if(child instanceof YagoClass) {
// super.addChild(child);
// }
// }
//
// public static List<YagoClass> getAccessibleUpwardYagoClasses(Collection<YagoClass> fromSubset) {
// Collection<HierarchyElement> accessible = HierarchyElement.getAccessibleUpwardElements(fromSubset);
// ArrayList<YagoClass> retVal = new ArrayList<>();
//
// for(HierarchyElement he : accessible) {
// retVal.add((YagoClass) he);
// }
//
// return retVal;
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/lattice/Concept.java
import dbpediaanalyzer.dbpediaobject.Category;
import dbpediaanalyzer.dbpediaobject.OntologyClass;
import dbpediaanalyzer.dbpediaobject.YagoClass;
import java.util.*;
package dbpediaanalyzer.lattice;
/**
* Concept of the annotated lattice
*
* @author Pierre Monnin
*
*/
public class Concept {
// Basic concept data
private List<String> objects;
private List<String> attributes;
// Relationships
private List<Concept> parents;
private List<Concept> children;
// Annotations
private List<Category> categories;
private List<OntologyClass> ontologyClasses; | private List<YagoClass> yagoClasses; |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/io/ComparisonResultsStatisticsWriter.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/statistic/ComparisonResultsStatistics.java
// public class ComparisonResultsStatistics {
// private ComparisonResultType type;
// private String uriPrefix;
// private int validNumber;
// private int invalidNumber;
// private Map<String, Double> averageValues;
// private Map<String, Double> minimumValues;
// private Map<String, Double> maximumValues;
//
// public ComparisonResultsStatistics(List<ComparisonResult> comparisonResults, ComparisonResultType type, String uriPrefix) {
// this.type = type;
// this.uriPrefix = uriPrefix;
// this.validNumber = 0;
// this.invalidNumber = 0;
// this.averageValues = new HashMap<>();
// this.minimumValues = new HashMap<>();
// this.maximumValues = new HashMap<>();
//
// for(ComparisonResult result : comparisonResults) {
// if(result.getType() == type && result.getBottom().getUri().startsWith(uriPrefix)) {
// if(result.isInvalid()) {
// this.invalidNumber++;
// }
//
// else {
// this.validNumber++;
//
// for(Map.Entry<String, Double> value : result.getValues().entrySet()) {
// if(!this.averageValues.containsKey(value.getKey())) {
// this.averageValues.put(value.getKey(), value.getValue());
// this.minimumValues.put(value.getKey(), value.getValue());
// this.maximumValues.put(value.getKey(), value.getValue());
// }
//
// else {
// if(value.getValue() < this.minimumValues.get(value.getKey())) {
// this.minimumValues.put(value.getKey(), value.getValue());
// }
//
// if(value.getValue() > this.maximumValues.get(value.getKey())) {
// this.maximumValues.put(value.getKey(), value.getValue());
// }
//
// this.averageValues.put(value.getKey(), this.averageValues.get(value.getKey()) + value.getValue());
// }
// }
// }
// }
// }
//
// if(this.validNumber != 0) {
// HashMap<String, Double> temp = new HashMap<>();
//
// for(Map.Entry<String, Double> average : this.averageValues.entrySet()) {
// temp.put(average.getKey(), average.getValue() / (double) this.validNumber);
// }
//
// this.averageValues = temp;
// }
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public String getUriPrefix() {
// return this.uriPrefix;
// }
//
// public int getValidNumber() {
// return this.validNumber;
// }
//
// public int getInvalidNumber() {
// return this.invalidNumber;
// }
//
// public Map<String, Double> getAverageValues() {
// return new HashMap<>(this.averageValues);
// }
//
// public Map<String, Double> getMinimumValues() {
// return new HashMap<>(this.minimumValues);
// }
//
// public Map<String, Double> getMaximumValues() {
// return new HashMap<>(this.maximumValues);
// }
//
// }
| import dbpediaanalyzer.statistic.ComparisonResultsStatistics;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map; | package dbpediaanalyzer.io;
/**
* Saves comparison results statistics in a file (JSON format)
*
* @author Pierre Monnin
*
*/
public class ComparisonResultsStatisticsWriter extends AbstractStatisticsWriter {
public ComparisonResultsStatisticsWriter(String fileName) {
super(fileName, "comparison results");
}
| // Path: DBPediaAnalyzer/src/dbpediaanalyzer/statistic/ComparisonResultsStatistics.java
// public class ComparisonResultsStatistics {
// private ComparisonResultType type;
// private String uriPrefix;
// private int validNumber;
// private int invalidNumber;
// private Map<String, Double> averageValues;
// private Map<String, Double> minimumValues;
// private Map<String, Double> maximumValues;
//
// public ComparisonResultsStatistics(List<ComparisonResult> comparisonResults, ComparisonResultType type, String uriPrefix) {
// this.type = type;
// this.uriPrefix = uriPrefix;
// this.validNumber = 0;
// this.invalidNumber = 0;
// this.averageValues = new HashMap<>();
// this.minimumValues = new HashMap<>();
// this.maximumValues = new HashMap<>();
//
// for(ComparisonResult result : comparisonResults) {
// if(result.getType() == type && result.getBottom().getUri().startsWith(uriPrefix)) {
// if(result.isInvalid()) {
// this.invalidNumber++;
// }
//
// else {
// this.validNumber++;
//
// for(Map.Entry<String, Double> value : result.getValues().entrySet()) {
// if(!this.averageValues.containsKey(value.getKey())) {
// this.averageValues.put(value.getKey(), value.getValue());
// this.minimumValues.put(value.getKey(), value.getValue());
// this.maximumValues.put(value.getKey(), value.getValue());
// }
//
// else {
// if(value.getValue() < this.minimumValues.get(value.getKey())) {
// this.minimumValues.put(value.getKey(), value.getValue());
// }
//
// if(value.getValue() > this.maximumValues.get(value.getKey())) {
// this.maximumValues.put(value.getKey(), value.getValue());
// }
//
// this.averageValues.put(value.getKey(), this.averageValues.get(value.getKey()) + value.getValue());
// }
// }
// }
// }
// }
//
// if(this.validNumber != 0) {
// HashMap<String, Double> temp = new HashMap<>();
//
// for(Map.Entry<String, Double> average : this.averageValues.entrySet()) {
// temp.put(average.getKey(), average.getValue() / (double) this.validNumber);
// }
//
// this.averageValues = temp;
// }
// }
//
// public ComparisonResultType getType() {
// return this.type;
// }
//
// public String getUriPrefix() {
// return this.uriPrefix;
// }
//
// public int getValidNumber() {
// return this.validNumber;
// }
//
// public int getInvalidNumber() {
// return this.invalidNumber;
// }
//
// public Map<String, Double> getAverageValues() {
// return new HashMap<>(this.averageValues);
// }
//
// public Map<String, Double> getMinimumValues() {
// return new HashMap<>(this.minimumValues);
// }
//
// public Map<String, Double> getMaximumValues() {
// return new HashMap<>(this.maximumValues);
// }
//
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/io/ComparisonResultsStatisticsWriter.java
import dbpediaanalyzer.statistic.ComparisonResultsStatistics;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
package dbpediaanalyzer.io;
/**
* Saves comparison results statistics in a file (JSON format)
*
* @author Pierre Monnin
*
*/
public class ComparisonResultsStatisticsWriter extends AbstractStatisticsWriter {
public ComparisonResultsStatisticsWriter(String fileName) {
super(fileName, "comparison results");
}
| public void writeComparisonResultsStatistics(ComparisonResultsStatistics crs) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
| import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption; | package dbpediaanalyzer.comparison;
/**
* Class representing an abstract strategy evaluating an axiom suggested by the annotated lattice
*
* @author Pierre Monnin
*
*/
public abstract class EvaluationStrategy {
public static final double INVALID_RESULT_VALUE = -1.0;
public abstract String getName();
| // Path: DBPediaAnalyzer/src/dbpediaanalyzer/databasedknowledge/DataBasedSubsumption.java
// public class DataBasedSubsumption {
// private HierarchyElement bottom;
// private HierarchyElement top;
// private List<Double> extensionsRatios;
// private List<Double> intensionsRatios;
//
// public DataBasedSubsumption(HierarchyElement bottom, HierarchyElement top, double extensionsRatio, double intensionsRatio) {
// this.bottom = bottom;
// this.top = top;
// this.extensionsRatios = new ArrayList<>();
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios = new ArrayList<>();
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public void newSubmission(double extensionsRatio, double intensionsRatio) {
// this.extensionsRatios.add(extensionsRatio);
// this.intensionsRatios.add(intensionsRatio);
// }
//
// public HierarchyElement getBottom() {
// return this.bottom;
// }
//
// public HierarchyElement getTop() {
// return this.top;
// }
//
// public int getNumberOfSubmissions() {
// return this.extensionsRatios.size();
// }
//
// public List<Double> getExtensionsRatios() {
// return new ArrayList<>(this.extensionsRatios);
// }
//
// public List<Double> getIntensionsRatios() {
// return new ArrayList<>(this.intensionsRatios);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/comparison/EvaluationStrategy.java
import dbpediaanalyzer.databasedknowledge.DataBasedSubsumption;
package dbpediaanalyzer.comparison;
/**
* Class representing an abstract strategy evaluating an axiom suggested by the annotated lattice
*
* @author Pierre Monnin
*
*/
public abstract class EvaluationStrategy {
public static final double INVALID_RESULT_VALUE = -1.0;
public abstract String getName();
| public double evaluateSubsumption(DataBasedSubsumption subsumption) { |
pmonnin/dbpedia-ontologies-mining | DBPediaAnalyzer/src/dbpediaanalyzer/main/DataInfo.java | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/HierarchiesFactory.java
// public class HierarchiesFactory {
//
// public static HierarchiesManager createHierarchies() {
// return new HierarchiesManager(createCategoriesHierarchy(), createOntologyClassesHierarchy(),
// createYagoClassesHierarchy());
// }
//
// private static Map<String, Category> createCategoriesHierarchy() {
// HierarchyFactory<Category> factory = new HierarchyFactory<>(new HierarchyElementFactory<Category>() {
// @Override
// public Category createHierarchyElement(String uri) {
// return new Category(uri);
// }
// }, "categories");
//
// String creationQueryPrefixes = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
// "PREFIX skos:<http://www.w3.org/2004/02/skos/core#> ";
// String creationQueryWhereClause = "?class rdf:type skos:Concept . ";
// String creationQueryUriPrefix = "http://dbpedia.org/resource/Category:";
// String parentsQueryPrefixes = "PREFIX skos:<http://www.w3.org/2004/02/skos/core#> ";
// String parentRelationship = "skos:broader";
// String parentsQueryUriPrefix = "http://dbpedia.org/resource/Category";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
//
// private static Map<String, OntologyClass> createOntologyClassesHierarchy() {
// HierarchyFactory<OntologyClass> factory = new HierarchyFactory<>(new HierarchyElementFactory<OntologyClass>() {
// @Override
// public OntologyClass createHierarchyElement(String uri) {
// return new OntologyClass(uri);
// }
// }, "ontology classes");
//
// String creationQueryPrefixes = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
// "PREFIX owl:<http://www.w3.org/2002/07/owl#> ";
// String creationQueryWhereClause = "?class rdf:type owl:Class . ";
// String creationQueryUriPrefix = "http://dbpedia.org/ontology/";
// String parentsQueryPrefixes = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> ";
// String parentRelationship = "rdfs:subClassOf";
// String parentsQueryUriPrefix = "http://dbpedia.org/ontology";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
//
// private static Map<String, YagoClass> createYagoClassesHierarchy() {
// HierarchyFactory<YagoClass> factory = new HierarchyFactory<>(new HierarchyElementFactory<YagoClass>() {
// @Override
// public YagoClass createHierarchyElement(String uri) {
// return new YagoClass(uri);
// }
// }, "yago classes");
//
// String creationQueryPrefixes = "PREFIX owl:<http://www.w3.org/2002/07/owl#> ";
// String creationQueryWhereClause = "?class owl:equivalentClass ?ec . " +
// "FILTER (REGEX(STR(?ec), \"http://yago-knowledge.org\", \"i\")) . ";
// String creationQueryUriPrefix = "http://dbpedia.org/class/yago/";
// String parentsQueryPrefixes = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> ";
// String parentRelationship = "rdfs:subClassOf";
// String parentsQueryUriPrefix = "http://dbpedia.org/class/yago";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
// }
| import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.factory.HierarchiesFactory;
import java.util.List;
import java.util.Scanner; | package dbpediaanalyzer.main;
/**
* This program can be used to display information or compute various results on ontology classes. It has the
* following features:
* - Display information about an ontology (parents and children)
* - Find path between two ontology classes
* - Display Lower Common Ancestor of two ontology classes
* - Display distance from closest top level class of an ontology class
* @author Pierre Monnin
*
*/
public class DataInfo {
public static void main(String[] args) {
System.out.println("=== DATA INFO ===");
System.out.println("Please wait... Setting up...");
System.out.println("\t Querying and parsing DBPedia hierarchies..."); | // Path: DBPediaAnalyzer/src/dbpediaanalyzer/factory/HierarchiesFactory.java
// public class HierarchiesFactory {
//
// public static HierarchiesManager createHierarchies() {
// return new HierarchiesManager(createCategoriesHierarchy(), createOntologyClassesHierarchy(),
// createYagoClassesHierarchy());
// }
//
// private static Map<String, Category> createCategoriesHierarchy() {
// HierarchyFactory<Category> factory = new HierarchyFactory<>(new HierarchyElementFactory<Category>() {
// @Override
// public Category createHierarchyElement(String uri) {
// return new Category(uri);
// }
// }, "categories");
//
// String creationQueryPrefixes = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
// "PREFIX skos:<http://www.w3.org/2004/02/skos/core#> ";
// String creationQueryWhereClause = "?class rdf:type skos:Concept . ";
// String creationQueryUriPrefix = "http://dbpedia.org/resource/Category:";
// String parentsQueryPrefixes = "PREFIX skos:<http://www.w3.org/2004/02/skos/core#> ";
// String parentRelationship = "skos:broader";
// String parentsQueryUriPrefix = "http://dbpedia.org/resource/Category";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
//
// private static Map<String, OntologyClass> createOntologyClassesHierarchy() {
// HierarchyFactory<OntologyClass> factory = new HierarchyFactory<>(new HierarchyElementFactory<OntologyClass>() {
// @Override
// public OntologyClass createHierarchyElement(String uri) {
// return new OntologyClass(uri);
// }
// }, "ontology classes");
//
// String creationQueryPrefixes = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
// "PREFIX owl:<http://www.w3.org/2002/07/owl#> ";
// String creationQueryWhereClause = "?class rdf:type owl:Class . ";
// String creationQueryUriPrefix = "http://dbpedia.org/ontology/";
// String parentsQueryPrefixes = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> ";
// String parentRelationship = "rdfs:subClassOf";
// String parentsQueryUriPrefix = "http://dbpedia.org/ontology";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
//
// private static Map<String, YagoClass> createYagoClassesHierarchy() {
// HierarchyFactory<YagoClass> factory = new HierarchyFactory<>(new HierarchyElementFactory<YagoClass>() {
// @Override
// public YagoClass createHierarchyElement(String uri) {
// return new YagoClass(uri);
// }
// }, "yago classes");
//
// String creationQueryPrefixes = "PREFIX owl:<http://www.w3.org/2002/07/owl#> ";
// String creationQueryWhereClause = "?class owl:equivalentClass ?ec . " +
// "FILTER (REGEX(STR(?ec), \"http://yago-knowledge.org\", \"i\")) . ";
// String creationQueryUriPrefix = "http://dbpedia.org/class/yago/";
// String parentsQueryPrefixes = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> ";
// String parentRelationship = "rdfs:subClassOf";
// String parentsQueryUriPrefix = "http://dbpedia.org/class/yago";
//
// return factory.createHierarchy(creationQueryPrefixes, creationQueryWhereClause, creationQueryUriPrefix,
// parentsQueryPrefixes, parentRelationship, parentsQueryUriPrefix);
// }
// }
// Path: DBPediaAnalyzer/src/dbpediaanalyzer/main/DataInfo.java
import dbpediaanalyzer.dbpediaobject.*;
import dbpediaanalyzer.factory.HierarchiesFactory;
import java.util.List;
import java.util.Scanner;
package dbpediaanalyzer.main;
/**
* This program can be used to display information or compute various results on ontology classes. It has the
* following features:
* - Display information about an ontology (parents and children)
* - Find path between two ontology classes
* - Display Lower Common Ancestor of two ontology classes
* - Display distance from closest top level class of an ontology class
* @author Pierre Monnin
*
*/
public class DataInfo {
public static void main(String[] args) {
System.out.println("=== DATA INFO ===");
System.out.println("Please wait... Setting up...");
System.out.println("\t Querying and parsing DBPedia hierarchies..."); | HierarchiesManager hm = HierarchiesFactory.createHierarchies(); |
KayLerch/alexa-morse-coder | skill/src/main/java/io/klerch/alexa/morse/skill/intents/LaunchHandler.java | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
| import io.klerch.alexa.morse.skill.SkillConfig;
import io.klerch.alexa.state.utils.AlexaStateException;
import io.klerch.alexa.tellask.model.AlexaInput;
import io.klerch.alexa.tellask.model.AlexaOutput;
import io.klerch.alexa.tellask.model.AlexaOutputSlot;
import io.klerch.alexa.tellask.schema.AlexaLaunchHandler;
import io.klerch.alexa.tellask.schema.annotation.AlexaLaunchListener;
import io.klerch.alexa.tellask.schema.type.AlexaOutputFormat;
import io.klerch.alexa.tellask.util.AlexaRequestHandlerException; | package io.klerch.alexa.morse.skill.intents;
@AlexaLaunchListener
public class LaunchHandler implements AlexaLaunchHandler {
@Override
public AlexaOutput handleRequest(final AlexaInput input) throws AlexaRequestHandlerException, AlexaStateException {
return AlexaOutput.ask("SayWelcome") | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
// Path: skill/src/main/java/io/klerch/alexa/morse/skill/intents/LaunchHandler.java
import io.klerch.alexa.morse.skill.SkillConfig;
import io.klerch.alexa.state.utils.AlexaStateException;
import io.klerch.alexa.tellask.model.AlexaInput;
import io.klerch.alexa.tellask.model.AlexaOutput;
import io.klerch.alexa.tellask.model.AlexaOutputSlot;
import io.klerch.alexa.tellask.schema.AlexaLaunchHandler;
import io.klerch.alexa.tellask.schema.annotation.AlexaLaunchListener;
import io.klerch.alexa.tellask.schema.type.AlexaOutputFormat;
import io.klerch.alexa.tellask.util.AlexaRequestHandlerException;
package io.klerch.alexa.morse.skill.intents;
@AlexaLaunchListener
public class LaunchHandler implements AlexaLaunchHandler {
@Override
public AlexaOutput handleRequest(final AlexaInput input) throws AlexaRequestHandlerException, AlexaStateException {
return AlexaOutput.ask("SayWelcome") | .putSlot(new AlexaOutputSlot("hi-mp3", SkillConfig.getMp3HiFileUrl()).formatAs(AlexaOutputFormat.AUDIO)) |
KayLerch/alexa-morse-coder | server/src/main/java/io/klerch/morse/config/JerseyConfig.java | // Path: server/src/main/java/io/klerch/morse/service/EncodeService.java
// @Component
// @Path("/encode")
// public class EncodeService {
// @Autowired
// private ImageUtils imageUtils;
//
// @Autowired
// private S3Utils s3Utils;
//
// @GET
// @Produces(MediaType.APPLICATION_JSON)
// public MorseCode getMorse(@QueryParam("text") String text, @QueryParam("wpm") Integer wpm, @QueryParam("fw") Integer fw) {
// return new MorseCode(s3Utils, imageUtils).load(text, wpm, fw != null ? fw : wpm);
// }
// }
| import io.klerch.morse.service.EncodeService;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component; | package io.klerch.morse.config;
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() { | // Path: server/src/main/java/io/klerch/morse/service/EncodeService.java
// @Component
// @Path("/encode")
// public class EncodeService {
// @Autowired
// private ImageUtils imageUtils;
//
// @Autowired
// private S3Utils s3Utils;
//
// @GET
// @Produces(MediaType.APPLICATION_JSON)
// public MorseCode getMorse(@QueryParam("text") String text, @QueryParam("wpm") Integer wpm, @QueryParam("fw") Integer fw) {
// return new MorseCode(s3Utils, imageUtils).load(text, wpm, fw != null ? fw : wpm);
// }
// }
// Path: server/src/main/java/io/klerch/morse/config/JerseyConfig.java
import io.klerch.morse.service.EncodeService;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
package io.klerch.morse.config;
@Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() { | register(EncodeService.class); |
KayLerch/alexa-morse-coder | skill/src/main/java/io/klerch/alexa/morse/skill/model/MorseUser.java | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
| import io.klerch.alexa.morse.skill.SkillConfig;
import io.klerch.alexa.state.model.AlexaScope;
import io.klerch.alexa.state.model.AlexaStateIgnore;
import io.klerch.alexa.state.model.AlexaStateModel;
import io.klerch.alexa.state.model.AlexaStateSave;
import io.klerch.alexa.state.utils.AlexaStateException;
import io.klerch.alexa.tellask.schema.annotation.AlexaSlotSave;
import io.klerch.alexa.tellask.schema.type.AlexaOutputFormat;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Optional; | package io.klerch.alexa.morse.skill.model;
@AlexaStateSave(Scope = AlexaScope.USER)
public class MorseUser extends AlexaStateModel {
@AlexaStateIgnore
private static final Logger log = Logger.getLogger(MorseUser.class);
private String userId;
private String name;
@AlexaSlotSave(slotName = "userScore", formatAs = AlexaOutputFormat.NUMBER)
private Integer personalScore = 0;
@AlexaSlotSave(slotName = "wpm", formatAs = AlexaOutputFormat.NUMBER) | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
// Path: skill/src/main/java/io/klerch/alexa/morse/skill/model/MorseUser.java
import io.klerch.alexa.morse.skill.SkillConfig;
import io.klerch.alexa.state.model.AlexaScope;
import io.klerch.alexa.state.model.AlexaStateIgnore;
import io.klerch.alexa.state.model.AlexaStateModel;
import io.klerch.alexa.state.model.AlexaStateSave;
import io.klerch.alexa.state.utils.AlexaStateException;
import io.klerch.alexa.tellask.schema.annotation.AlexaSlotSave;
import io.klerch.alexa.tellask.schema.type.AlexaOutputFormat;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Optional;
package io.klerch.alexa.morse.skill.model;
@AlexaStateSave(Scope = AlexaScope.USER)
public class MorseUser extends AlexaStateModel {
@AlexaStateIgnore
private static final Logger log = Logger.getLogger(MorseUser.class);
private String userId;
private String name;
@AlexaSlotSave(slotName = "userScore", formatAs = AlexaOutputFormat.NUMBER)
private Integer personalScore = 0;
@AlexaSlotSave(slotName = "wpm", formatAs = AlexaOutputFormat.NUMBER) | private Integer wpm = SkillConfig.getWpmLevelDefault(); |
KayLerch/alexa-morse-coder | skill/src/test/java/io/klerch/alexa/morse/skill/model/MorseUserTest.java | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
| import io.klerch.alexa.morse.skill.SkillConfig;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.*; | final MorseUser user2 = user.withPersonalScore(10);
assertEquals(user, user2);
assertEquals(new Integer(10), user2.getPersonalScore());
user.withPersonalScore(-3);
assertEquals(new Integer(0), user2.getPersonalScore());
user.withPersonalScore(null);
assertEquals(new Integer(0), user2.getPersonalScore());
}
@Test
public void withIncreasedPersonalScoreBy() throws Exception {
user.setPersonalScore(10);
final MorseUser user2 = user.withIncreasedPersonalScoreBy(5);
assertEquals(user, user2);
assertEquals(new Integer(15), user2.getPersonalScore());
}
@Test
public void withDecreasedPersonalScoreBy() throws Exception {
user.setPersonalScore(10);
final MorseUser user2 = user.withDecreasedPersonalScoreBy(5);
assertEquals(user, user2);
assertEquals(new Integer(5), user2.getPersonalScore());
user2.withDecreasedPersonalScoreBy(10);
assertEquals(new Integer(0), user2.getPersonalScore());
}
@Test
public void getSetWpm() throws Exception {
// max | // Path: skill/src/main/java/io/klerch/alexa/morse/skill/SkillConfig.java
// public class SkillConfig {
// private static Properties properties = new Properties();
// private static final String defaultPropertiesFile = "app.properties";
// private static final String customPropertiesFile = "my.app.properties";
//
// // some constants not worth having them in a properties-files
// public static final Integer ScoreDecreaseOnRetry = 1;
// public static final Integer ScoreDecreaseOnSkipped = 2;
// public static final Integer ScoreDecreaseOnFarnsworth = 3;
//
// /**
// * Static block does the bootstrapping of all configuration properties with
// * reading out values from different resource files
// */
// static {
// final String propertiesFile =
// SkillConfig.class.getClassLoader().getResource(customPropertiesFile) != null ?
// customPropertiesFile : defaultPropertiesFile;
// final InputStream propertiesStream = SkillConfig.class.getClassLoader().getResourceAsStream(propertiesFile);
// try {
// properties.load(propertiesStream);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (propertiesStream != null) {
// try {
// propertiesStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
//
// /**
// * Application-id which should be supported by this skill implementation
// */
// public static String getAlexaAppId() {
// return properties.getProperty("AlexaAppId");
// }
//
// public static String getAlexaSlotIntroductionName() {
// return properties.getProperty("AlexaSlotIntroductionName");
// }
// public static String getAlexaSlotIntroductionSignA() {
// return properties.getProperty("AlexaSlotIntroductionSignA");
// }
// public static String getAlexaSlotIntroductionSignB() {
// return properties.getProperty("AlexaSlotIntroductionSignB");
// }
// public static String getAlexaSlotIntroductionSignC() {
// return properties.getProperty("AlexaSlotIntroductionSignC");
// }
// public static String getAlexaSlotIntroductionSignD() {
// return properties.getProperty("AlexaSlotIntroductionSignD");
// }
// public static String getAlexaSlotIntroductionSignE() {
// return properties.getProperty("AlexaSlotIntroductionSignE");
// }
// public static String getAlexaSlotIntroductionSignF() {
// return properties.getProperty("AlexaSlotIntroductionSignF");
// }
// public static String getAlexaSlotIntroductionSignG() {
// return properties.getProperty("AlexaSlotIntroductionSignG");
// }
// public static String getAlexaSlotIntroductionSignH() {
// return properties.getProperty("AlexaSlotIntroductionSignH");
// }
//
// /**
// * Name of the slot which holds a first name to either be spelled or encoded to morse code
// */
// public static String getAlexaSlotEncodePhrase() {
// return properties.getProperty("AlexaSlotEncodePhrase");
// }
//
// /**
// * Name of the slot which holds the answer (guessed word) of a user during an exercise
// */
// public static String getAlexaSlotExerciseWord() {
// return properties.getProperty("AlexaSlotExerciseWord");
// }
//
// public static String getAlexaSlotCfgWpm() {
// return properties.getProperty("AlexaSlotCfgWpm");
// }
//
// /**
// * Url of the S3-bucket where all audio-files of morse codes are stored in
// */
// public static String getMorseCoderAPIuser() {
// return properties.getProperty("MorseCoderAPIuser");
// }
//
// public static String getMorseCoderAPIpass() {
// return properties.getProperty("MorseCoderAPIpass");
// }
//
// public static String getMorseCoderAPIencode() {
// return properties.getProperty("MorseCoderAPIencode");
// }
//
// public static String getS3BucketUrl() {
// return properties.getProperty("S3BucketUrl");
// }
//
// public static String getMp3HiFileUrl() {
// return properties.getProperty("S3BucketUrl") + properties.getProperty("Mp3HiFilename");
// }
//
// public static Integer getWpmLevelMin() {
// return Integer.valueOf(properties.getProperty("WpmLevelMin"));
// }
//
// public static Integer getWpmLevelDefault() {
// return Integer.valueOf(properties.getProperty("WpmLevelDefault"));
// }
//
// public static Integer getWpmLevelMax() {
// return Integer.valueOf(properties.getProperty("WpmLevelMax"));
// }
//
// public static Integer getWpmLevelStep() {
// return Integer.valueOf(properties.getProperty("WpmLevelStep"));
// }
//
// public static Integer getFarnsworthWpmReduction() {
// return Integer.valueOf(properties.getProperty("FarnsworthWpmReduction"));
// }
//
// public static Boolean shouldExposeIoTHook() {
// return Boolean.valueOf(properties.getProperty("ExposeIoTHook"));
// }
// }
// Path: skill/src/test/java/io/klerch/alexa/morse/skill/model/MorseUserTest.java
import io.klerch.alexa.morse.skill.SkillConfig;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.*;
final MorseUser user2 = user.withPersonalScore(10);
assertEquals(user, user2);
assertEquals(new Integer(10), user2.getPersonalScore());
user.withPersonalScore(-3);
assertEquals(new Integer(0), user2.getPersonalScore());
user.withPersonalScore(null);
assertEquals(new Integer(0), user2.getPersonalScore());
}
@Test
public void withIncreasedPersonalScoreBy() throws Exception {
user.setPersonalScore(10);
final MorseUser user2 = user.withIncreasedPersonalScoreBy(5);
assertEquals(user, user2);
assertEquals(new Integer(15), user2.getPersonalScore());
}
@Test
public void withDecreasedPersonalScoreBy() throws Exception {
user.setPersonalScore(10);
final MorseUser user2 = user.withDecreasedPersonalScoreBy(5);
assertEquals(user, user2);
assertEquals(new Integer(5), user2.getPersonalScore());
user2.withDecreasedPersonalScoreBy(10);
assertEquals(new Integer(0), user2.getPersonalScore());
}
@Test
public void getSetWpm() throws Exception {
// max | user.setWpm(SkillConfig.getWpmLevelMax()); |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/RegisterInfo.java | // Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
| import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils; |
public Builder addExtra(String key, Number value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == numberExtrasBuilder) {
numberExtrasBuilder = new HashMap<String, Number>();
}
numberExtrasBuilder.put(key, value);
return this;
}
public Builder addExtra(String key, Boolean value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == booleanExtrasBuilder) {
booleanExtrasBuilder = new HashMap<String, Boolean>();
}
booleanExtrasBuilder.put(key, value);
return this;
}
public Builder addExtra(String key, JsonObject value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == jsonExtrasBuilder) {
jsonExtrasBuilder = new HashMap<String, JsonObject>();
}
jsonExtrasBuilder.put(key, value);
return this;
}
public RegisterInfo build() {
| // Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
// Path: src/main/java/cn/jmessage/api/common/model/RegisterInfo.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils;
public Builder addExtra(String key, Number value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == numberExtrasBuilder) {
numberExtrasBuilder = new HashMap<String, Number>();
}
numberExtrasBuilder.put(key, value);
return this;
}
public Builder addExtra(String key, Boolean value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == booleanExtrasBuilder) {
booleanExtrasBuilder = new HashMap<String, Boolean>();
}
booleanExtrasBuilder.put(key, value);
return this;
}
public Builder addExtra(String key, JsonObject value) {
Preconditions.checkArgument(! (null == key || null == value), "Key/Value should not be null.");
if (null == jsonExtrasBuilder) {
jsonExtrasBuilder = new HashMap<String, JsonObject>();
}
jsonExtrasBuilder.put(key, value);
return this;
}
public RegisterInfo build() {
| StringUtils.checkUsername(username); |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/resource/ResourceClient.java | // Path: src/main/java/cn/jmessage/api/common/BaseClient.java
// public class BaseClient {
//
// protected IHttpClient _httpClient;
// protected String _baseUrl;
// protected Gson _gson = new Gson();
//
// /**
// * Create a JMessage Base Client
// *
// * @param appKey The KEY of one application on JPush.
// * @param masterSecret API access secret of the appKey.
// * @param proxy The proxy, if there is no proxy, should be null.
// * @param config The client configuration. Can use JMessageConfig.getInstance() as default.
// */
// public BaseClient(String appKey, String masterSecret, HttpProxy proxy, JMessageConfig config) {
// ServiceHelper.checkBasic(appKey, masterSecret);
// String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
// this._baseUrl = (String) config.get(JMessageConfig.API_HOST_NAME);
// this._httpClient = new NativeHttpClient(authCode, proxy, config.getClientConfig());
// }
//
// public void setHttpClient(IHttpClient httpClient) {
// this._httpClient = httpClient;
// }
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/JMessageConfig.java
// public class JMessageConfig {
//
// private static ClientConfig clientConfig = ClientConfig.getInstance();
//
// private static JMessageConfig instance = new JMessageConfig();
//
// public static final String API_HOST_NAME = "im.api.host.name";
// public static final String API_REPORT_HOST_NAME = "im.api.report.host.name";
//
// public static final String ADMIN_PATH = "im.admin.path";
//
// public static final String USER_PATH = "im.user.path";
// public static final String V2_USER_PATH = "im.v2.user.path";
//
// public static final String GROUP_PATH = "im.group.path";
// public static final String V2_GROUP_PATH = "im.v2.group.path";
//
// public static final String MESSAGE_PATH = "im.message.path";
// public static final String V2_MESSAGE_PATH = "im.v2.message.path";
// public static final String V2_STATISTIC_PATH = "im.v2.statistic.path";
// public static final String V2_CHATROOM_PATH = "im.v2.chatroom.path";
//
// public static final String RESOURCE_PATH = "im.resource.path";
//
// public static final String CROSS_USER_PATH = "im.cross.user.path";
// public static final String CROSS_GROUP_PATH = "im.cross.group.path";
//
// public static final String SENSITIVE_WORD_PATH = "im.sensitive.word.path";
//
// public static final String CHAT_ROOM_PATH = "im.chat.room.path";
//
// public static final String MAX_RETRY_TIMES = ClientConfig.MAX_RETRY_TIMES;
//
// public static final String SEND_VERSION = "send.version";
// public static final Object SEND_VERSION_SCHMEA = Integer.class;
//
// private JMessageConfig() {
// clientConfig.put(API_HOST_NAME, "https://api.im.jpush.cn");
// clientConfig.put(API_REPORT_HOST_NAME, "https://report.im.jpush.cn");
// clientConfig.put(ADMIN_PATH, "/v1/admins");
// clientConfig.put(USER_PATH, "/v1/users");
// clientConfig.put(V2_USER_PATH, "/v2/users");
// clientConfig.put(GROUP_PATH, "/v1/groups");
// clientConfig.put(V2_GROUP_PATH, "/v2/groups");
// clientConfig.put(MESSAGE_PATH, "/v1/messages");
// clientConfig.put(V2_MESSAGE_PATH, "/v2/messages");
// clientConfig.put(RESOURCE_PATH, "/v1/resource");
// clientConfig.put(CROSS_USER_PATH, "/v1/cross/users");
// clientConfig.put(CROSS_GROUP_PATH, "/v1/cross/groups");
// clientConfig.put(SENSITIVE_WORD_PATH, "/v1/sensitiveword");
// clientConfig.put(CHAT_ROOM_PATH, "/v1/chatroom");
// clientConfig.put(V2_CHATROOM_PATH, "/v2/chatrooms");
// clientConfig.put(V2_STATISTIC_PATH, "/v2/statistic");
// clientConfig.put(MAX_RETRY_TIMES, 3);
// clientConfig.put(SEND_VERSION, 1);
// }
//
// public static JMessageConfig getInstance() {
// return instance;
// }
//
// public ClientConfig getClientConfig() {
// return clientConfig;
// }
//
// public JMessageConfig setApiHostName(String hostName) {
// clientConfig.put(API_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setReportHostName(String hostName) {
// clientConfig.put(API_REPORT_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setMaxRetryTimes(int maxRetryTimes) {
// clientConfig.setMaxRetryTimes(maxRetryTimes);
// return this;
// }
//
// public void put(String key, Object value) {
// clientConfig.put(key, value);
// }
//
// public Object get(String key) {
// return clientConfig.get(key);
// }
//
// }
| import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.utils.Preconditions;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.common.BaseClient;
import cn.jmessage.api.common.JMessageConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL; | package cn.jmessage.api.resource;
public class ResourceClient extends BaseClient {
private static Logger LOG = LoggerFactory.getLogger(ResourceClient.class);
private String resourcePath;
private String authCode;
public ResourceClient(String appkey, String masterSecret) { | // Path: src/main/java/cn/jmessage/api/common/BaseClient.java
// public class BaseClient {
//
// protected IHttpClient _httpClient;
// protected String _baseUrl;
// protected Gson _gson = new Gson();
//
// /**
// * Create a JMessage Base Client
// *
// * @param appKey The KEY of one application on JPush.
// * @param masterSecret API access secret of the appKey.
// * @param proxy The proxy, if there is no proxy, should be null.
// * @param config The client configuration. Can use JMessageConfig.getInstance() as default.
// */
// public BaseClient(String appKey, String masterSecret, HttpProxy proxy, JMessageConfig config) {
// ServiceHelper.checkBasic(appKey, masterSecret);
// String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
// this._baseUrl = (String) config.get(JMessageConfig.API_HOST_NAME);
// this._httpClient = new NativeHttpClient(authCode, proxy, config.getClientConfig());
// }
//
// public void setHttpClient(IHttpClient httpClient) {
// this._httpClient = httpClient;
// }
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/JMessageConfig.java
// public class JMessageConfig {
//
// private static ClientConfig clientConfig = ClientConfig.getInstance();
//
// private static JMessageConfig instance = new JMessageConfig();
//
// public static final String API_HOST_NAME = "im.api.host.name";
// public static final String API_REPORT_HOST_NAME = "im.api.report.host.name";
//
// public static final String ADMIN_PATH = "im.admin.path";
//
// public static final String USER_PATH = "im.user.path";
// public static final String V2_USER_PATH = "im.v2.user.path";
//
// public static final String GROUP_PATH = "im.group.path";
// public static final String V2_GROUP_PATH = "im.v2.group.path";
//
// public static final String MESSAGE_PATH = "im.message.path";
// public static final String V2_MESSAGE_PATH = "im.v2.message.path";
// public static final String V2_STATISTIC_PATH = "im.v2.statistic.path";
// public static final String V2_CHATROOM_PATH = "im.v2.chatroom.path";
//
// public static final String RESOURCE_PATH = "im.resource.path";
//
// public static final String CROSS_USER_PATH = "im.cross.user.path";
// public static final String CROSS_GROUP_PATH = "im.cross.group.path";
//
// public static final String SENSITIVE_WORD_PATH = "im.sensitive.word.path";
//
// public static final String CHAT_ROOM_PATH = "im.chat.room.path";
//
// public static final String MAX_RETRY_TIMES = ClientConfig.MAX_RETRY_TIMES;
//
// public static final String SEND_VERSION = "send.version";
// public static final Object SEND_VERSION_SCHMEA = Integer.class;
//
// private JMessageConfig() {
// clientConfig.put(API_HOST_NAME, "https://api.im.jpush.cn");
// clientConfig.put(API_REPORT_HOST_NAME, "https://report.im.jpush.cn");
// clientConfig.put(ADMIN_PATH, "/v1/admins");
// clientConfig.put(USER_PATH, "/v1/users");
// clientConfig.put(V2_USER_PATH, "/v2/users");
// clientConfig.put(GROUP_PATH, "/v1/groups");
// clientConfig.put(V2_GROUP_PATH, "/v2/groups");
// clientConfig.put(MESSAGE_PATH, "/v1/messages");
// clientConfig.put(V2_MESSAGE_PATH, "/v2/messages");
// clientConfig.put(RESOURCE_PATH, "/v1/resource");
// clientConfig.put(CROSS_USER_PATH, "/v1/cross/users");
// clientConfig.put(CROSS_GROUP_PATH, "/v1/cross/groups");
// clientConfig.put(SENSITIVE_WORD_PATH, "/v1/sensitiveword");
// clientConfig.put(CHAT_ROOM_PATH, "/v1/chatroom");
// clientConfig.put(V2_CHATROOM_PATH, "/v2/chatrooms");
// clientConfig.put(V2_STATISTIC_PATH, "/v2/statistic");
// clientConfig.put(MAX_RETRY_TIMES, 3);
// clientConfig.put(SEND_VERSION, 1);
// }
//
// public static JMessageConfig getInstance() {
// return instance;
// }
//
// public ClientConfig getClientConfig() {
// return clientConfig;
// }
//
// public JMessageConfig setApiHostName(String hostName) {
// clientConfig.put(API_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setReportHostName(String hostName) {
// clientConfig.put(API_REPORT_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setMaxRetryTimes(int maxRetryTimes) {
// clientConfig.setMaxRetryTimes(maxRetryTimes);
// return this;
// }
//
// public void put(String key, Object value) {
// clientConfig.put(key, value);
// }
//
// public Object get(String key) {
// return clientConfig.get(key);
// }
//
// }
// Path: src/main/java/cn/jmessage/api/resource/ResourceClient.java
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.utils.Preconditions;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.common.BaseClient;
import cn.jmessage.api.common.JMessageConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
package cn.jmessage.api.resource;
public class ResourceClient extends BaseClient {
private static Logger LOG = LoggerFactory.getLogger(ResourceClient.class);
private String resourcePath;
private String authCode;
public ResourceClient(String appkey, String masterSecret) { | this(appkey, masterSecret, null, JMessageConfig.getInstance()); |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/sensitiveword/SensitiveWordClient.java | // Path: src/main/java/cn/jmessage/api/common/BaseClient.java
// public class BaseClient {
//
// protected IHttpClient _httpClient;
// protected String _baseUrl;
// protected Gson _gson = new Gson();
//
// /**
// * Create a JMessage Base Client
// *
// * @param appKey The KEY of one application on JPush.
// * @param masterSecret API access secret of the appKey.
// * @param proxy The proxy, if there is no proxy, should be null.
// * @param config The client configuration. Can use JMessageConfig.getInstance() as default.
// */
// public BaseClient(String appKey, String masterSecret, HttpProxy proxy, JMessageConfig config) {
// ServiceHelper.checkBasic(appKey, masterSecret);
// String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
// this._baseUrl = (String) config.get(JMessageConfig.API_HOST_NAME);
// this._httpClient = new NativeHttpClient(authCode, proxy, config.getClientConfig());
// }
//
// public void setHttpClient(IHttpClient httpClient) {
// this._httpClient = httpClient;
// }
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/JMessageConfig.java
// public class JMessageConfig {
//
// private static ClientConfig clientConfig = ClientConfig.getInstance();
//
// private static JMessageConfig instance = new JMessageConfig();
//
// public static final String API_HOST_NAME = "im.api.host.name";
// public static final String API_REPORT_HOST_NAME = "im.api.report.host.name";
//
// public static final String ADMIN_PATH = "im.admin.path";
//
// public static final String USER_PATH = "im.user.path";
// public static final String V2_USER_PATH = "im.v2.user.path";
//
// public static final String GROUP_PATH = "im.group.path";
// public static final String V2_GROUP_PATH = "im.v2.group.path";
//
// public static final String MESSAGE_PATH = "im.message.path";
// public static final String V2_MESSAGE_PATH = "im.v2.message.path";
// public static final String V2_STATISTIC_PATH = "im.v2.statistic.path";
// public static final String V2_CHATROOM_PATH = "im.v2.chatroom.path";
//
// public static final String RESOURCE_PATH = "im.resource.path";
//
// public static final String CROSS_USER_PATH = "im.cross.user.path";
// public static final String CROSS_GROUP_PATH = "im.cross.group.path";
//
// public static final String SENSITIVE_WORD_PATH = "im.sensitive.word.path";
//
// public static final String CHAT_ROOM_PATH = "im.chat.room.path";
//
// public static final String MAX_RETRY_TIMES = ClientConfig.MAX_RETRY_TIMES;
//
// public static final String SEND_VERSION = "send.version";
// public static final Object SEND_VERSION_SCHMEA = Integer.class;
//
// private JMessageConfig() {
// clientConfig.put(API_HOST_NAME, "https://api.im.jpush.cn");
// clientConfig.put(API_REPORT_HOST_NAME, "https://report.im.jpush.cn");
// clientConfig.put(ADMIN_PATH, "/v1/admins");
// clientConfig.put(USER_PATH, "/v1/users");
// clientConfig.put(V2_USER_PATH, "/v2/users");
// clientConfig.put(GROUP_PATH, "/v1/groups");
// clientConfig.put(V2_GROUP_PATH, "/v2/groups");
// clientConfig.put(MESSAGE_PATH, "/v1/messages");
// clientConfig.put(V2_MESSAGE_PATH, "/v2/messages");
// clientConfig.put(RESOURCE_PATH, "/v1/resource");
// clientConfig.put(CROSS_USER_PATH, "/v1/cross/users");
// clientConfig.put(CROSS_GROUP_PATH, "/v1/cross/groups");
// clientConfig.put(SENSITIVE_WORD_PATH, "/v1/sensitiveword");
// clientConfig.put(CHAT_ROOM_PATH, "/v1/chatroom");
// clientConfig.put(V2_CHATROOM_PATH, "/v2/chatrooms");
// clientConfig.put(V2_STATISTIC_PATH, "/v2/statistic");
// clientConfig.put(MAX_RETRY_TIMES, 3);
// clientConfig.put(SEND_VERSION, 1);
// }
//
// public static JMessageConfig getInstance() {
// return instance;
// }
//
// public ClientConfig getClientConfig() {
// return clientConfig;
// }
//
// public JMessageConfig setApiHostName(String hostName) {
// clientConfig.put(API_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setReportHostName(String hostName) {
// clientConfig.put(API_REPORT_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setMaxRetryTimes(int maxRetryTimes) {
// clientConfig.setMaxRetryTimes(maxRetryTimes);
// return this;
// }
//
// public void put(String key, Object value) {
// clientConfig.put(key, value);
// }
//
// public Object get(String key) {
// return clientConfig.get(key);
// }
//
// }
| import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.common.BaseClient;
import cn.jmessage.api.common.JMessageConfig;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.util.Set; | package cn.jmessage.api.sensitiveword;
public class SensitiveWordClient extends BaseClient {
private String sensitiveWordPath;
public SensitiveWordClient(String appKey, String masterSecret) { | // Path: src/main/java/cn/jmessage/api/common/BaseClient.java
// public class BaseClient {
//
// protected IHttpClient _httpClient;
// protected String _baseUrl;
// protected Gson _gson = new Gson();
//
// /**
// * Create a JMessage Base Client
// *
// * @param appKey The KEY of one application on JPush.
// * @param masterSecret API access secret of the appKey.
// * @param proxy The proxy, if there is no proxy, should be null.
// * @param config The client configuration. Can use JMessageConfig.getInstance() as default.
// */
// public BaseClient(String appKey, String masterSecret, HttpProxy proxy, JMessageConfig config) {
// ServiceHelper.checkBasic(appKey, masterSecret);
// String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
// this._baseUrl = (String) config.get(JMessageConfig.API_HOST_NAME);
// this._httpClient = new NativeHttpClient(authCode, proxy, config.getClientConfig());
// }
//
// public void setHttpClient(IHttpClient httpClient) {
// this._httpClient = httpClient;
// }
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/JMessageConfig.java
// public class JMessageConfig {
//
// private static ClientConfig clientConfig = ClientConfig.getInstance();
//
// private static JMessageConfig instance = new JMessageConfig();
//
// public static final String API_HOST_NAME = "im.api.host.name";
// public static final String API_REPORT_HOST_NAME = "im.api.report.host.name";
//
// public static final String ADMIN_PATH = "im.admin.path";
//
// public static final String USER_PATH = "im.user.path";
// public static final String V2_USER_PATH = "im.v2.user.path";
//
// public static final String GROUP_PATH = "im.group.path";
// public static final String V2_GROUP_PATH = "im.v2.group.path";
//
// public static final String MESSAGE_PATH = "im.message.path";
// public static final String V2_MESSAGE_PATH = "im.v2.message.path";
// public static final String V2_STATISTIC_PATH = "im.v2.statistic.path";
// public static final String V2_CHATROOM_PATH = "im.v2.chatroom.path";
//
// public static final String RESOURCE_PATH = "im.resource.path";
//
// public static final String CROSS_USER_PATH = "im.cross.user.path";
// public static final String CROSS_GROUP_PATH = "im.cross.group.path";
//
// public static final String SENSITIVE_WORD_PATH = "im.sensitive.word.path";
//
// public static final String CHAT_ROOM_PATH = "im.chat.room.path";
//
// public static final String MAX_RETRY_TIMES = ClientConfig.MAX_RETRY_TIMES;
//
// public static final String SEND_VERSION = "send.version";
// public static final Object SEND_VERSION_SCHMEA = Integer.class;
//
// private JMessageConfig() {
// clientConfig.put(API_HOST_NAME, "https://api.im.jpush.cn");
// clientConfig.put(API_REPORT_HOST_NAME, "https://report.im.jpush.cn");
// clientConfig.put(ADMIN_PATH, "/v1/admins");
// clientConfig.put(USER_PATH, "/v1/users");
// clientConfig.put(V2_USER_PATH, "/v2/users");
// clientConfig.put(GROUP_PATH, "/v1/groups");
// clientConfig.put(V2_GROUP_PATH, "/v2/groups");
// clientConfig.put(MESSAGE_PATH, "/v1/messages");
// clientConfig.put(V2_MESSAGE_PATH, "/v2/messages");
// clientConfig.put(RESOURCE_PATH, "/v1/resource");
// clientConfig.put(CROSS_USER_PATH, "/v1/cross/users");
// clientConfig.put(CROSS_GROUP_PATH, "/v1/cross/groups");
// clientConfig.put(SENSITIVE_WORD_PATH, "/v1/sensitiveword");
// clientConfig.put(CHAT_ROOM_PATH, "/v1/chatroom");
// clientConfig.put(V2_CHATROOM_PATH, "/v2/chatrooms");
// clientConfig.put(V2_STATISTIC_PATH, "/v2/statistic");
// clientConfig.put(MAX_RETRY_TIMES, 3);
// clientConfig.put(SEND_VERSION, 1);
// }
//
// public static JMessageConfig getInstance() {
// return instance;
// }
//
// public ClientConfig getClientConfig() {
// return clientConfig;
// }
//
// public JMessageConfig setApiHostName(String hostName) {
// clientConfig.put(API_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setReportHostName(String hostName) {
// clientConfig.put(API_REPORT_HOST_NAME, hostName);
// return this;
// }
//
// public JMessageConfig setMaxRetryTimes(int maxRetryTimes) {
// clientConfig.setMaxRetryTimes(maxRetryTimes);
// return this;
// }
//
// public void put(String key, Object value) {
// clientConfig.put(key, value);
// }
//
// public Object get(String key) {
// return clientConfig.get(key);
// }
//
// }
// Path: src/main/java/cn/jmessage/api/sensitiveword/SensitiveWordClient.java
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.common.BaseClient;
import cn.jmessage.api.common.JMessageConfig;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.util.Set;
package cn.jmessage.api.sensitiveword;
public class SensitiveWordClient extends BaseClient {
private String sensitiveWordPath;
public SensitiveWordClient(String appKey, String masterSecret) { | this(appKey, masterSecret, null, JMessageConfig.getInstance()); |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/message/MessagePayload.java | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/message/MessageType.java
// public enum MessageType {
// TEXT("text"),
// IMAGE("image"),
// VOICE("voice"),
// CUSTOM("custom");
//
// private String value;
//
// private MessageType(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
| import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.message.MessageType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils; | package cn.jmessage.api.common.model.message;
/**
* MessagePayload https://docs.jiguang.cn/jmessage/server/rest_api_im/#_17
*/
public class MessagePayload implements IModel {
private static final String VERSION = "version";
private static final String TARGET_TYPE = "target_type";
private static final String FROM_TYPE = "from_type";
private static final String MSG_TYPE = "msg_type";
private static final String TARGET_ID = "target_id";
private static final String FROM_ID = "from_id";
private static final String TARGET_APP_KEY = "target_appkey";
private static final String FROM_NAME = "from_name";
private static final String TARGET_NAME = "target_name";
private static final String MSG_BODY = "msg_body";
private static final String NO_OFFLINE = "no_offline";
private static final String NO_NOTIFICATION = "no_notification";
private static final String NOTIFICATION = "notification";
private static Gson gson = new Gson();
private Integer mVersion;
private String mTargetType;
private String mTargetId;
private String mFromType;
private String mFromId;
private String mTargetAppKey;
private String mFromName;
private String mTargetName;
// 默认为false,表示需要离线存储
private boolean mNoOffline = false;
// 默认为false,表示在通知栏展示
private boolean mNoNotification = false; | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/message/MessageType.java
// public enum MessageType {
// TEXT("text"),
// IMAGE("image"),
// VOICE("voice"),
// CUSTOM("custom");
//
// private String value;
//
// private MessageType(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
// Path: src/main/java/cn/jmessage/api/common/model/message/MessagePayload.java
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.message.MessageType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils;
package cn.jmessage.api.common.model.message;
/**
* MessagePayload https://docs.jiguang.cn/jmessage/server/rest_api_im/#_17
*/
public class MessagePayload implements IModel {
private static final String VERSION = "version";
private static final String TARGET_TYPE = "target_type";
private static final String FROM_TYPE = "from_type";
private static final String MSG_TYPE = "msg_type";
private static final String TARGET_ID = "target_id";
private static final String FROM_ID = "from_id";
private static final String TARGET_APP_KEY = "target_appkey";
private static final String FROM_NAME = "from_name";
private static final String TARGET_NAME = "target_name";
private static final String MSG_BODY = "msg_body";
private static final String NO_OFFLINE = "no_offline";
private static final String NO_NOTIFICATION = "no_notification";
private static final String NOTIFICATION = "notification";
private static Gson gson = new Gson();
private Integer mVersion;
private String mTargetType;
private String mTargetId;
private String mFromType;
private String mFromId;
private String mTargetAppKey;
private String mFromName;
private String mTargetName;
// 默认为false,表示需要离线存储
private boolean mNoOffline = false;
// 默认为false,表示在通知栏展示
private boolean mNoNotification = false; | private MessageType mMsgType; |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/message/MessagePayload.java | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/message/MessageType.java
// public enum MessageType {
// TEXT("text"),
// IMAGE("image"),
// VOICE("voice"),
// CUSTOM("custom");
//
// private String value;
//
// private MessageType(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
| import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.message.MessageType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils; | return this;
}
public Builder setNoOffline(boolean noOffline) {
this.mNoOffline = noOffline;
return this;
}
public Builder setNoNotification(boolean noNotification) {
this.mNoNotification = noNotification;
return this;
}
public Builder setMessageType(MessageType msgType) {
this.mMsgType = msgType;
return this;
}
public Builder setMessageBody(MessageBody msgBody) {
this.mMsgBody = msgBody;
return this;
}
public Builder setNotification(Notification notification) {
this.mNotification = notification;
return this;
}
public MessagePayload build() {
Preconditions.checkArgument(null != mVersion, "The version must not be empty!"); | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/message/MessageType.java
// public enum MessageType {
// TEXT("text"),
// IMAGE("image"),
// VOICE("voice"),
// CUSTOM("custom");
//
// private String value;
//
// private MessageType(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
// Path: src/main/java/cn/jmessage/api/common/model/message/MessagePayload.java
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.message.MessageType;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.utils.StringUtils;
return this;
}
public Builder setNoOffline(boolean noOffline) {
this.mNoOffline = noOffline;
return this;
}
public Builder setNoNotification(boolean noNotification) {
this.mNoNotification = noNotification;
return this;
}
public Builder setMessageType(MessageType msgType) {
this.mMsgType = msgType;
return this;
}
public Builder setMessageBody(MessageBody msgBody) {
this.mMsgBody = msgBody;
return this;
}
public Builder setNotification(Notification notification) {
this.mNotification = notification;
return this;
}
public MessagePayload build() {
Preconditions.checkArgument(null != mVersion, "The version must not be empty!"); | Preconditions.checkArgument(StringUtils.isNotEmpty(mTargetType), "The target type must not be empty!"); |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/friend/FriendNote.java | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
| import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.UnsupportedEncodingException; | this.note_name = note_name;
this.others = others;
this.username = username;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String note_name;
private String others;
private String username;
public Builder setNoteName(String noteName) {
this.note_name = noteName;
return this;
}
public Builder setOthers(String others) {
this.others = others;
return this;
}
public Builder setUsername(String username) {
this.username = username;
return this;
}
public FriendNote builder() { | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/utils/StringUtils.java
// public class StringUtils {
//
// public static void checkUsername(String username) {
// if ( null == username || username.trim().length() == 0) {
// throw new IllegalArgumentException("username must not be empty");
// }
// if (username.contains("\n") || username.contains("\r") || username.contains("\t")) {
// throw new IllegalArgumentException("username must not contain line feed character");
// }
// byte[] usernameByte = username.getBytes();
// if (usernameByte.length < 4 || usernameByte.length > 128) {
// throw new IllegalArgumentException("The length of username must between 4 and 128 bytes. Input is " + username);
// }
// if (!ServiceHelper.checkUsername(username)) {
// throw new IllegalArgumentException("The parameter username contains illegal character," +
// " a-zA-Z_0-9.、-,@。 is legally, and start with alphabet or number. Input is " + username);
// }
// }
//
// public static void checkPassword(String password) {
// if (null == password || password.trim().length() == 0) {
// throw new IllegalArgumentException("password must not be empty");
// }
//
// byte[] passwordByte = password.getBytes();
// if (passwordByte.length < 4 || passwordByte.length > 128) {
// throw new IllegalArgumentException("The length of password must between 4 and 128 bytes. Input is " + password);
// }
//
// }
//
// public static boolean isNotEmpty(String s) {
// return s != null && s.length() > 0;
// }
//
// public static boolean isTrimedEmpty(String s) {
// return s == null || s.trim().length() == 0;
// }
//
// public static boolean isLineBroken(String s) {
// if (s.contains("\n") || s.contains("\r")) {
// return true;
// }
// return false;
// }
//
// }
// Path: src/main/java/cn/jmessage/api/common/model/friend/FriendNote.java
import cn.jiguang.common.utils.Preconditions;
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.UnsupportedEncodingException;
this.note_name = note_name;
this.others = others;
this.username = username;
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String note_name;
private String others;
private String username;
public Builder setNoteName(String noteName) {
this.note_name = noteName;
return this;
}
public Builder setOthers(String others) {
this.others = others;
return this;
}
public Builder setUsername(String username) {
this.username = username;
return this;
}
public FriendNote builder() { | StringUtils.checkUsername(username); |
jpush/jmessage-api-java-client | example/main/java/cn/jmessage/api/examples/ChatRoomExample.java | // Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java
// public class ChatRoomPayload implements IModel {
//
// public static final String OWNER = "owner_username";
// public static final String NAME = "name";
// public static final String MEMBERS = "members_username";
// public static final String DESC = "description";
// public static final String FLAG = "flag";
//
// private static Gson gson = new Gson();
//
// private String owner;
// private String name;
// private Members members;
// private String desc;
// // 禁言标志,0 表示不禁言,1 表示禁言
// private int flag = -1;
//
// public ChatRoomPayload(String name, String ownerName, Members members, String desc, int flag) {
// this.name = name;
// this.owner = ownerName;
// this.members = members;
// this.desc = desc;
// this.flag = flag;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
//
// @Override
// public JsonElement toJSON() {
// JsonObject jsonObject = new JsonObject();
// if (null != name) {
// jsonObject.addProperty(NAME, name);
// }
//
// if (null != owner) {
// jsonObject.addProperty(OWNER, owner);
// }
//
// if ( null != members ) {
// jsonObject.add(MEMBERS, members.toJSON());
// }
//
// if ( null != desc ) {
// jsonObject.addProperty(DESC, desc);
// }
//
// if (flag != -1) {
// jsonObject.addProperty(FLAG, flag);
// }
//
// return jsonObject;
// }
//
// public static class Builder {
// private String owner;
// private String name;
// private Members members;
// private String desc;
// private int flag = -1;
//
// public Builder setName(String name) {
// this.name = name;
// return this;
// }
//
// public Builder setOwnerUsername(String owner) {
// this.owner = owner;
// return this;
// }
//
// public Builder setMembers(Members members) {
// this.members = members;
// return this;
// }
//
// public Builder setDesc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public Builder setFlag(int flag) {
// this.flag = flag;
// return this;
// }
//
// public ChatRoomPayload build() {
// return new ChatRoomPayload(name, owner, members, desc, flag);
// }
//
// }
//
// @Override
// public String toString() {
// return gson.toJson(toJSON());
// }
// }
| import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.chatroom.*;
import cn.jmessage.api.common.model.Members;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package cn.jmessage.api.examples;
public class ChatRoomExample {
private static Logger LOG = LoggerFactory.getLogger(ChatRoomExample.class);
private static final String appkey = "242780bfdd7315dc1989fe2b";
private static final String masterSecret = "2f5ced2bef64167950e63d13";
private ChatRoomClient mClient = new ChatRoomClient(appkey, masterSecret);
public static void main(String[] args) {
}
public void testCreateChatRoom() {
try { | // Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java
// public class ChatRoomPayload implements IModel {
//
// public static final String OWNER = "owner_username";
// public static final String NAME = "name";
// public static final String MEMBERS = "members_username";
// public static final String DESC = "description";
// public static final String FLAG = "flag";
//
// private static Gson gson = new Gson();
//
// private String owner;
// private String name;
// private Members members;
// private String desc;
// // 禁言标志,0 表示不禁言,1 表示禁言
// private int flag = -1;
//
// public ChatRoomPayload(String name, String ownerName, Members members, String desc, int flag) {
// this.name = name;
// this.owner = ownerName;
// this.members = members;
// this.desc = desc;
// this.flag = flag;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
//
// @Override
// public JsonElement toJSON() {
// JsonObject jsonObject = new JsonObject();
// if (null != name) {
// jsonObject.addProperty(NAME, name);
// }
//
// if (null != owner) {
// jsonObject.addProperty(OWNER, owner);
// }
//
// if ( null != members ) {
// jsonObject.add(MEMBERS, members.toJSON());
// }
//
// if ( null != desc ) {
// jsonObject.addProperty(DESC, desc);
// }
//
// if (flag != -1) {
// jsonObject.addProperty(FLAG, flag);
// }
//
// return jsonObject;
// }
//
// public static class Builder {
// private String owner;
// private String name;
// private Members members;
// private String desc;
// private int flag = -1;
//
// public Builder setName(String name) {
// this.name = name;
// return this;
// }
//
// public Builder setOwnerUsername(String owner) {
// this.owner = owner;
// return this;
// }
//
// public Builder setMembers(Members members) {
// this.members = members;
// return this;
// }
//
// public Builder setDesc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public Builder setFlag(int flag) {
// this.flag = flag;
// return this;
// }
//
// public ChatRoomPayload build() {
// return new ChatRoomPayload(name, owner, members, desc, flag);
// }
//
// }
//
// @Override
// public String toString() {
// return gson.toJson(toJSON());
// }
// }
// Path: example/main/java/cn/jmessage/api/examples/ChatRoomExample.java
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.chatroom.*;
import cn.jmessage.api.common.model.Members;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package cn.jmessage.api.examples;
public class ChatRoomExample {
private static Logger LOG = LoggerFactory.getLogger(ChatRoomExample.class);
private static final String appkey = "242780bfdd7315dc1989fe2b";
private static final String masterSecret = "2f5ced2bef64167950e63d13";
private ChatRoomClient mClient = new ChatRoomClient(appkey, masterSecret);
public static void main(String[] args) {
}
public void testCreateChatRoom() {
try { | ChatRoomPayload payload = ChatRoomPayload.newBuilder() |
jpush/jmessage-api-java-client | example/main/java/cn/jmessage/api/examples/ChatRoomExample.java | // Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java
// public class ChatRoomPayload implements IModel {
//
// public static final String OWNER = "owner_username";
// public static final String NAME = "name";
// public static final String MEMBERS = "members_username";
// public static final String DESC = "description";
// public static final String FLAG = "flag";
//
// private static Gson gson = new Gson();
//
// private String owner;
// private String name;
// private Members members;
// private String desc;
// // 禁言标志,0 表示不禁言,1 表示禁言
// private int flag = -1;
//
// public ChatRoomPayload(String name, String ownerName, Members members, String desc, int flag) {
// this.name = name;
// this.owner = ownerName;
// this.members = members;
// this.desc = desc;
// this.flag = flag;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
//
// @Override
// public JsonElement toJSON() {
// JsonObject jsonObject = new JsonObject();
// if (null != name) {
// jsonObject.addProperty(NAME, name);
// }
//
// if (null != owner) {
// jsonObject.addProperty(OWNER, owner);
// }
//
// if ( null != members ) {
// jsonObject.add(MEMBERS, members.toJSON());
// }
//
// if ( null != desc ) {
// jsonObject.addProperty(DESC, desc);
// }
//
// if (flag != -1) {
// jsonObject.addProperty(FLAG, flag);
// }
//
// return jsonObject;
// }
//
// public static class Builder {
// private String owner;
// private String name;
// private Members members;
// private String desc;
// private int flag = -1;
//
// public Builder setName(String name) {
// this.name = name;
// return this;
// }
//
// public Builder setOwnerUsername(String owner) {
// this.owner = owner;
// return this;
// }
//
// public Builder setMembers(Members members) {
// this.members = members;
// return this;
// }
//
// public Builder setDesc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public Builder setFlag(int flag) {
// this.flag = flag;
// return this;
// }
//
// public ChatRoomPayload build() {
// return new ChatRoomPayload(name, owner, members, desc, flag);
// }
//
// }
//
// @Override
// public String toString() {
// return gson.toJson(toJSON());
// }
// }
| import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.chatroom.*;
import cn.jmessage.api.common.model.Members;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package cn.jmessage.api.examples;
public class ChatRoomExample {
private static Logger LOG = LoggerFactory.getLogger(ChatRoomExample.class);
private static final String appkey = "242780bfdd7315dc1989fe2b";
private static final String masterSecret = "2f5ced2bef64167950e63d13";
private ChatRoomClient mClient = new ChatRoomClient(appkey, masterSecret);
public static void main(String[] args) {
}
public void testCreateChatRoom() {
try {
ChatRoomPayload payload = ChatRoomPayload.newBuilder()
.setName("haha")
.setDesc("test")
.setOwnerUsername("junit_admin") | // Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java
// public class ChatRoomPayload implements IModel {
//
// public static final String OWNER = "owner_username";
// public static final String NAME = "name";
// public static final String MEMBERS = "members_username";
// public static final String DESC = "description";
// public static final String FLAG = "flag";
//
// private static Gson gson = new Gson();
//
// private String owner;
// private String name;
// private Members members;
// private String desc;
// // 禁言标志,0 表示不禁言,1 表示禁言
// private int flag = -1;
//
// public ChatRoomPayload(String name, String ownerName, Members members, String desc, int flag) {
// this.name = name;
// this.owner = ownerName;
// this.members = members;
// this.desc = desc;
// this.flag = flag;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
//
// @Override
// public JsonElement toJSON() {
// JsonObject jsonObject = new JsonObject();
// if (null != name) {
// jsonObject.addProperty(NAME, name);
// }
//
// if (null != owner) {
// jsonObject.addProperty(OWNER, owner);
// }
//
// if ( null != members ) {
// jsonObject.add(MEMBERS, members.toJSON());
// }
//
// if ( null != desc ) {
// jsonObject.addProperty(DESC, desc);
// }
//
// if (flag != -1) {
// jsonObject.addProperty(FLAG, flag);
// }
//
// return jsonObject;
// }
//
// public static class Builder {
// private String owner;
// private String name;
// private Members members;
// private String desc;
// private int flag = -1;
//
// public Builder setName(String name) {
// this.name = name;
// return this;
// }
//
// public Builder setOwnerUsername(String owner) {
// this.owner = owner;
// return this;
// }
//
// public Builder setMembers(Members members) {
// this.members = members;
// return this;
// }
//
// public Builder setDesc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public Builder setFlag(int flag) {
// this.flag = flag;
// return this;
// }
//
// public ChatRoomPayload build() {
// return new ChatRoomPayload(name, owner, members, desc, flag);
// }
//
// }
//
// @Override
// public String toString() {
// return gson.toJson(toJSON());
// }
// }
// Path: example/main/java/cn/jmessage/api/examples/ChatRoomExample.java
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.chatroom.*;
import cn.jmessage.api.common.model.Members;
import cn.jmessage.api.common.model.chatroom.ChatRoomPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package cn.jmessage.api.examples;
public class ChatRoomExample {
private static Logger LOG = LoggerFactory.getLogger(ChatRoomExample.class);
private static final String appkey = "242780bfdd7315dc1989fe2b";
private static final String masterSecret = "2f5ced2bef64167950e63d13";
private ChatRoomClient mClient = new ChatRoomClient(appkey, masterSecret);
public static void main(String[] args) {
}
public void testCreateChatRoom() {
try {
ChatRoomPayload payload = ChatRoomPayload.newBuilder()
.setName("haha")
.setDesc("test")
.setOwnerUsername("junit_admin") | .setMembers(Members.newBuilder().addMember("junit_user1", "junit_user2").build()) |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/group/GroupPayload.java | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
| import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.common.model.Members;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jiguang.common.utils.StringUtils; | package cn.jmessage.api.common.model.group;
public class GroupPayload implements IModel {
public static final String OWNER = "owner_username";
public static final String GROUP_NAME = "name";
public static final String MEMBERS = "members_username";
public static final String DESC = "desc";
public static final String AVATAR = "avatar";
public static final String FLAG = "flag";
private static Gson gson = new Gson();
private String owner;
private String name; | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
// Path: src/main/java/cn/jmessage/api/common/model/group/GroupPayload.java
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.common.model.Members;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import cn.jiguang.common.utils.Preconditions;
import cn.jiguang.common.utils.StringUtils;
package cn.jmessage.api.common.model.group;
public class GroupPayload implements IModel {
public static final String OWNER = "owner_username";
public static final String GROUP_NAME = "name";
public static final String MEMBERS = "members_username";
public static final String DESC = "desc";
public static final String AVATAR = "avatar";
public static final String FLAG = "flag";
private static Gson gson = new Gson();
private String owner;
private String name; | private Members members; |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
| import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.common.model.Members;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; | package cn.jmessage.api.common.model.chatroom;
public class ChatRoomPayload implements IModel {
public static final String OWNER = "owner_username";
public static final String NAME = "name";
public static final String MEMBERS = "members_username";
public static final String DESC = "description";
public static final String FLAG = "flag";
private static Gson gson = new Gson();
private String owner;
private String name; | // Path: src/main/java/cn/jmessage/api/common/model/IModel.java
// public interface IModel {
//
// public JsonElement toJSON();
//
// }
//
// Path: src/main/java/cn/jmessage/api/common/model/Members.java
// public class Members implements IModel {
//
// private JsonArray members;
//
// private Members(JsonArray members) {
// this.members = members;
// }
//
// public static Builder newBuilder() {
// return new Builder();
// }
//
// @Override
// public JsonElement toJSON() {
// return members;
// }
//
// public static class Builder {
//
// private JsonArray members = new JsonArray();
//
// public Builder addMember(String... usernames) {
//
// if( null == usernames ) {
// return this;
// }
//
// for (String username : usernames) {
// JsonPrimitive member = new JsonPrimitive(username);
// this.members.add(member);
// }
// return this;
// }
//
// public Members build() {
// return new Members(members);
// }
// }
// }
// Path: src/main/java/cn/jmessage/api/common/model/chatroom/ChatRoomPayload.java
import cn.jmessage.api.common.model.IModel;
import cn.jmessage.api.common.model.Members;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
package cn.jmessage.api.common.model.chatroom;
public class ChatRoomPayload implements IModel {
public static final String OWNER = "owner_username";
public static final String NAME = "name";
public static final String MEMBERS = "members_username";
public static final String DESC = "description";
public static final String FLAG = "flag";
private static Gson gson = new Gson();
private String owner;
private String name; | private Members members; |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/genalg/GA.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/dataparser/Utils.java
// public class Utils {
//
// public static final String FILE_SUFFIX = "_MSFT_tick.csv";
// public static final String pathToInput = "data\\";//put the absolute path to the data folder
//
// public static final String pathToEvaluation = "results\\evaluations\\";
// public static final String pathToTraining = "results\\trainings\\";
// public static final String pathToVisualisation = "results\\visualisations\\";
//
// public static final int STARTING_YEAR = 2014;
// public static final int STARTING_MONTH = 0;
// public static final int STARTING_DAY = 30;
// public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");
//
// public static String[] dataFileNames = {"20140130_MSFT_tick.csv",
// "20140131_MSFT_tick.csv",
// "20140203_MSFT_tick.csv",
// "20140204_MSFT_tick.csv",
// "20140205_MSFT_tick.csv",
// "20140206_MSFT_tick.csv",
// "20140207_MSFT_tick.csv",
// "20140210_MSFT_tick.csv",
// "20140211_MSFT_tick.csv",
// "20140212_MSFT_tick.csv",
// "20140213_MSFT_tick.csv",
// "20140214_MSFT_tick.csv",
// "20140218_MSFT_tick.csv",
// "20140219_MSFT_tick.csv",
// "20140220_MSFT_tick.csv",
// "20140221_MSFT_tick.csv",
// "20140224_MSFT_tick.csv",
// "20140225_MSFT_tick.csv",
// "20140226_MSFT_tick.csv",
// "20140227_MSFT_tick.csv",
// "20140228_MSFT_tick.csv",
// "20140303_MSFT_tick.csv",
// "20140304_MSFT_tick.csv",
// "20140305_MSFT_tick.csv",
// "20140306_MSFT_tick.csv",
// "20140307_MSFT_tick.csv",
// "20140310_MSFT_tick.csv",
// "20140311_MSFT_tick.csv",
// "20140312_MSFT_tick.csv",
// "20140313_MSFT_tick.csv",
// "20140314_MSFT_tick.csv",
// "20140317_MSFT_tick.csv",
// "20140318_MSFT_tick.csv",
// "20140319_MSFT_tick.csv",
// "20140320_MSFT_tick.csv",
// "20140321_MSFT_tick.csv",
// "20140324_MSFT_tick.csv",
// "20140325_MSFT_tick.csv",
// "20140326_MSFT_tick.csv",
// "20140327_MSFT_tick.csv",
// "20140328_MSFT_tick.csv",
// "20140331_MSFT_tick.csv"};
//
// /**
// * @param filename - fileName in data folder
// * @return
// * @throws FileNotFoundException
// */
// public static List<Tick> readCSV(String filename) throws FileNotFoundException {
//
// List<Tick> result = new ArrayList<Tick>();
// File file = new File(pathToInput + filename);
// Scanner scanner = new Scanner(file);
//
// while (scanner.hasNext()) {
// String line = scanner.nextLine();
// String data[] = line.split(",");
// Long orderId = Long.parseLong(data[0]);
// Long timestamp = Long.parseLong(data[1]);
// Long numberShares = Long.parseLong(data[3]);
// Long price = Long.parseLong(data[4]);
// result.add(new Tick(orderId, timestamp, numberShares, price));
// }
//
// Collections.sort(result);
//
// return result;
// }
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.dataparser.Utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Scanner;
import java.util.logging.FileHandler; | package ch.epfl.bigdata.ts.genalg;
/**
* Created by dorwi on 05.04.14.
*/
public class GA {
// Create an initial population
public static Population population = new Population(Constants.MAX_INDIVIDUALS, true);
//public static StockParameters stock_parameters = new StockParameters();
/*
public static void send_values(long time, double price) {
for (int i = 0; i < population.size(); i++) {
population.getIndividual(i).trade(time, price);
}
}
*/ | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/dataparser/Utils.java
// public class Utils {
//
// public static final String FILE_SUFFIX = "_MSFT_tick.csv";
// public static final String pathToInput = "data\\";//put the absolute path to the data folder
//
// public static final String pathToEvaluation = "results\\evaluations\\";
// public static final String pathToTraining = "results\\trainings\\";
// public static final String pathToVisualisation = "results\\visualisations\\";
//
// public static final int STARTING_YEAR = 2014;
// public static final int STARTING_MONTH = 0;
// public static final int STARTING_DAY = 30;
// public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");
//
// public static String[] dataFileNames = {"20140130_MSFT_tick.csv",
// "20140131_MSFT_tick.csv",
// "20140203_MSFT_tick.csv",
// "20140204_MSFT_tick.csv",
// "20140205_MSFT_tick.csv",
// "20140206_MSFT_tick.csv",
// "20140207_MSFT_tick.csv",
// "20140210_MSFT_tick.csv",
// "20140211_MSFT_tick.csv",
// "20140212_MSFT_tick.csv",
// "20140213_MSFT_tick.csv",
// "20140214_MSFT_tick.csv",
// "20140218_MSFT_tick.csv",
// "20140219_MSFT_tick.csv",
// "20140220_MSFT_tick.csv",
// "20140221_MSFT_tick.csv",
// "20140224_MSFT_tick.csv",
// "20140225_MSFT_tick.csv",
// "20140226_MSFT_tick.csv",
// "20140227_MSFT_tick.csv",
// "20140228_MSFT_tick.csv",
// "20140303_MSFT_tick.csv",
// "20140304_MSFT_tick.csv",
// "20140305_MSFT_tick.csv",
// "20140306_MSFT_tick.csv",
// "20140307_MSFT_tick.csv",
// "20140310_MSFT_tick.csv",
// "20140311_MSFT_tick.csv",
// "20140312_MSFT_tick.csv",
// "20140313_MSFT_tick.csv",
// "20140314_MSFT_tick.csv",
// "20140317_MSFT_tick.csv",
// "20140318_MSFT_tick.csv",
// "20140319_MSFT_tick.csv",
// "20140320_MSFT_tick.csv",
// "20140321_MSFT_tick.csv",
// "20140324_MSFT_tick.csv",
// "20140325_MSFT_tick.csv",
// "20140326_MSFT_tick.csv",
// "20140327_MSFT_tick.csv",
// "20140328_MSFT_tick.csv",
// "20140331_MSFT_tick.csv"};
//
// /**
// * @param filename - fileName in data folder
// * @return
// * @throws FileNotFoundException
// */
// public static List<Tick> readCSV(String filename) throws FileNotFoundException {
//
// List<Tick> result = new ArrayList<Tick>();
// File file = new File(pathToInput + filename);
// Scanner scanner = new Scanner(file);
//
// while (scanner.hasNext()) {
// String line = scanner.nextLine();
// String data[] = line.split(",");
// Long orderId = Long.parseLong(data[0]);
// Long timestamp = Long.parseLong(data[1]);
// Long numberShares = Long.parseLong(data[3]);
// Long price = Long.parseLong(data[4]);
// result.add(new Tick(orderId, timestamp, numberShares, price));
// }
//
// Collections.sort(result);
//
// return result;
// }
// }
// Path: src/ch/epfl/bigdata/ts/genalg/GA.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.dataparser.Utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Scanner;
import java.util.logging.FileHandler;
package ch.epfl.bigdata.ts.genalg;
/**
* Created by dorwi on 05.04.14.
*/
public class GA {
// Create an initial population
public static Population population = new Population(Constants.MAX_INDIVIDUALS, true);
//public static StockParameters stock_parameters = new StockParameters();
/*
public static void send_values(long time, double price) {
for (int i = 0; i < population.size(); i++) {
population.getIndividual(i).trade(time, price);
}
}
*/ | public static void send_values(Tick tick) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/RandomFirtness.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class RandomFirtness extends FitnessFunction {
private Random rand = new Random();
public RandomFirtness(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/RandomFirtness.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class RandomFirtness extends FitnessFunction {
private Random rand = new Random();
public RandomFirtness(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| public void calcFitness(Chromosome chr, boolean logForViz) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/RandomFirtness.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class RandomFirtness extends FitnessFunction {
private Random rand = new Random();
public RandomFirtness(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public void calcFitness(Chromosome chr, boolean logForViz) {
init();
int numberOfTransactions = 0;
for (int i = 0; i < numOfDaysInGeneration; i++) {
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/RandomFirtness.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class RandomFirtness extends FitnessFunction {
private Random rand = new Random();
public RandomFirtness(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public void calcFitness(Chromosome chr, boolean logForViz) {
init();
int numberOfTransactions = 0;
for (int i = 0; i < numOfDaysInGeneration; i++) {
| List<Tick> ticks1 = data.get(startForData + i); |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/UniformCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class UniformCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/UniformCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class UniformCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| Chromosome offspring = new Chromosome(new ArrayList<Gene>());
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/UniformCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class UniformCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
Chromosome offspring = new Chromosome(new ArrayList<Gene>());
for(int i = 0; i < chr1.getNumGenes(); i++) {
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/UniformCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class UniformCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
Chromosome offspring = new Chromosome(new ArrayList<Gene>());
for(int i = 0; i < chr1.getNumGenes(); i++) {
| double pickParentGene = Range.R.nextDouble();
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class Rectangle extends FitnessFunction {
public static final int GENE_DIST_EQUAL_LEVELS = 0;
public static final int GENE_DIFF_TOPS = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1, bottom2;
private double top1, top2;
private double sellLoss;
private double sellGain;
public Rectangle(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "Rectangle";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new Rectangle(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class Rectangle extends FitnessFunction {
public static final int GENE_DIST_EQUAL_LEVELS = 0;
public static final int GENE_DIFF_TOPS = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1, bottom2;
private double top1, top2;
private double sellLoss;
private double sellGain;
public Rectangle(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "Rectangle";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new Rectangle(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class Rectangle extends FitnessFunction {
public static final int GENE_DIST_EQUAL_LEVELS = 0;
public static final int GENE_DIFF_TOPS = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1, bottom2;
private double top1, top2;
private double sellLoss;
private double sellGain;
public Rectangle(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "Rectangle";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new Rectangle(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class Rectangle extends FitnessFunction {
public static final int GENE_DIST_EQUAL_LEVELS = 0;
public static final int GENE_DIFF_TOPS = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1, bottom2;
private double top1, top2;
private double sellLoss;
private double sellGain;
public Rectangle(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "Rectangle";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new Rectangle(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | vizLog.append("," + amount + "," + numOfShares);
}
vizLog.append("\n");
}
return toRet;
}
private void initPattern() {
bottom1 = bottom2 = -1;
top1 = top2 = -1;
}
protected void init() {
initPattern();
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
numOfShares = 0;
}
private void sell() {
openPosition = false;
amount += numOfShares * lastPrice;
numOfShares = 0;
initPattern();
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/Rectangle.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
vizLog.append("," + amount + "," + numOfShares);
}
vizLog.append("\n");
}
return toRet;
}
private void initPattern() {
bottom1 = bottom2 = -1;
top1 = top2 = -1;
}
protected void init() {
initPattern();
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
numOfShares = 0;
}
private void sell() {
openPosition = false;
amount += numOfShares * lastPrice;
numOfShares = 0;
initPattern();
}
| public static List<Range> getGeneRanges() { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/TwoPointCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class TwoPointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/TwoPointCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class TwoPointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| double pickFirstChr = Range.R.nextDouble();
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/TwoPointCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class TwoPointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
double pickFirstChr = Range.R.nextDouble();
int crossoverPoint1 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
int crossoverPoint2 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
while(crossoverPoint2 == crossoverPoint1) {
crossoverPoint2 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
}
if(crossoverPoint1 > crossoverPoint2) {
int tmp = crossoverPoint1;
crossoverPoint1 = crossoverPoint2;
crossoverPoint2 = tmp;
}
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/TwoPointCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class TwoPointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
double pickFirstChr = Range.R.nextDouble();
int crossoverPoint1 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
int crossoverPoint2 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
while(crossoverPoint2 == crossoverPoint1) {
crossoverPoint2 = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
}
if(crossoverPoint1 > crossoverPoint2) {
int tmp = crossoverPoint1;
crossoverPoint1 = crossoverPoint2;
crossoverPoint2 = tmp;
}
| Chromosome offspring = new Chromosome(new ArrayList<Gene>());
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleTop extends FitnessFunction {
public static final int GENE_TOP_1 = 0;
public static final int GENE_TOP_2 = 1;
public static final int GENE_PROTECT_BUY_GAIN = 2;
public static final int GENE_PROTECT_BUY_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double top1;
private double top2;
private double bottom;
private double buyLoss;
private double buyGain;
private boolean first = true;
public DoubleTop(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "DoubleTop";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new DoubleTop(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleTop extends FitnessFunction {
public static final int GENE_TOP_1 = 0;
public static final int GENE_TOP_2 = 1;
public static final int GENE_PROTECT_BUY_GAIN = 2;
public static final int GENE_PROTECT_BUY_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double top1;
private double top2;
private double bottom;
private double buyLoss;
private double buyGain;
private boolean first = true;
public DoubleTop(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "DoubleTop";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new DoubleTop(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleTop extends FitnessFunction {
public static final int GENE_TOP_1 = 0;
public static final int GENE_TOP_2 = 1;
public static final int GENE_PROTECT_BUY_GAIN = 2;
public static final int GENE_PROTECT_BUY_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double top1;
private double top2;
private double bottom;
private double buyLoss;
private double buyGain;
private boolean first = true;
public DoubleTop(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "DoubleTop";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new DoubleTop(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleTop extends FitnessFunction {
public static final int GENE_TOP_1 = 0;
public static final int GENE_TOP_2 = 1;
public static final int GENE_PROTECT_BUY_GAIN = 2;
public static final int GENE_PROTECT_BUY_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double top1;
private double top2;
private double bottom;
private double buyLoss;
private double buyGain;
private boolean first = true;
public DoubleTop(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public String getName() {
return "DoubleTop";
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new DoubleTop(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | vizLog.append("," + buyGain);
vizLog.append("," + buyLoss);
if (sold == 1 || bought == 1 || order == 0) {
vizLog.append("," + amount + "," + numOfShares);
}
vizLog.append("\n");
}
return toRet;
}
protected void init() {
top1 = -1;
top2 = -1;
bottom = -1;
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
first = true;
}
private void buy() {
openPosition = false;
numOfShares = (int) Math.floor(amount / lastPrice);
amount -= numOfShares * lastPrice;
top2 = bottom = -1;
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleTop.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
vizLog.append("," + buyGain);
vizLog.append("," + buyLoss);
if (sold == 1 || bought == 1 || order == 0) {
vizLog.append("," + amount + "," + numOfShares);
}
vizLog.append("\n");
}
return toRet;
}
protected void init() {
top1 = -1;
top2 = -1;
bottom = -1;
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
first = true;
}
private void buy() {
openPosition = false;
numOfShares = (int) Math.floor(amount / lastPrice);
amount -= numOfShares * lastPrice;
top2 = bottom = -1;
}
| public static List<Range> getGeneRanges() { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/Population.java | // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
| // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/Population.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
| private CrossoverMethod crossMethod;
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/Population.java | // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
private CrossoverMethod crossMethod;
| // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/Population.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
private CrossoverMethod crossMethod;
| private MutationMethod mutatMethod;
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/Population.java | // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
private CrossoverMethod crossMethod;
private MutationMethod mutatMethod;
private int maxPopulationSize;
| // Path: src/ch/epfl/bigdata/ts/ga/crossover/CrossoverMethod.java
// public interface CrossoverMethod {
// Chromosome cross(Chromosome chr1, Chromosome chr2);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/mutation/MutationMethod.java
// public interface MutationMethod {
// void mutate(Gene gene, Range range);
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
// public abstract class SelectionMethod {
//
// public abstract List<Chromosome> select(List<Chromosome> population, int n);
//
// protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
// for(int i = 1; i < population.size(); i++) {
// Chromosome prev = population.get(i - 1), cur = population.get(i);
// cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
// }
//
// List<Chromosome> result = new ArrayList<Chromosome>();
// for(int i = 0; i < n; i++) {
// double rVal = Range.R.nextDouble() * sum;
//
// for(int j = 0; j < population.size(); j++) {
// Chromosome cur = population.get(j);
// if(cur.getFitnessSelection() > rVal) {
// result.add(cur);
// break;
// }
// }
//
// }
// return result;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/Population.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import ch.epfl.bigdata.ts.ga.crossover.CrossoverMethod;
import ch.epfl.bigdata.ts.ga.mutation.MutationMethod;
import ch.epfl.bigdata.ts.ga.selection.SelectionMethod;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga;
public class Population {
private SelectionMethod selMethod;
private CrossoverMethod crossMethod;
private MutationMethod mutatMethod;
private int maxPopulationSize;
| private HashMap<String, Range> geneRange;
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/SinglePointCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class SinglePointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/SinglePointCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class SinglePointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
| double pickFirstChr = Range.R.nextDouble();
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/crossover/SinglePointCrossover.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.crossover;
public class SinglePointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
double pickFirstChr = Range.R.nextDouble();
int crossoverPoint = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Gene.java
// public class Gene {
// private double value;
// String name = "";
//
// public Gene(String name, double value) {
// this.name = name;
// this.value = value;
// }
//
// public Gene(double value) {
// this.value = value;
// }
//
// public Gene(Gene gene) {
// this(gene.name, gene.value);
// }
//
// public String getName() {
// return name;
// }
//
// public double getValue() {
// return value;
// }
//
// public void setValue(double value) {
// this.value = value;
// }
//
// public String toString() {
// return name + " " + value + " ";
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/crossover/SinglePointCrossover.java
import java.util.ArrayList;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.Gene;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.crossover;
public class SinglePointCrossover implements CrossoverMethod {
public Chromosome cross(Chromosome chr1, Chromosome chr2) {
double pickFirstChr = Range.R.nextDouble();
int crossoverPoint = 1 + Range.R.nextInt(chr1.getNumGenes() - 1);
| Chromosome offspring = new Chromosome(new ArrayList<Gene>());
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java | // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
| package ch.epfl.bigdata.ts.ga.selection;
public abstract class SelectionMethod {
public abstract List<Chromosome> select(List<Chromosome> population, int n);
protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
for(int i = 1; i < population.size(); i++) {
Chromosome prev = population.get(i - 1), cur = population.get(i);
cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
}
List<Chromosome> result = new ArrayList<Chromosome>();
for(int i = 0; i < n; i++) {
| // Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/ga/selection/SelectionMethod.java
import java.util.ArrayList;
import java.util.List;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
package ch.epfl.bigdata.ts.ga.selection;
public abstract class SelectionMethod {
public abstract List<Chromosome> select(List<Chromosome> population, int n);
protected List<Chromosome> throwMarble(List<Chromosome> population, int n, double sum) {
for(int i = 1; i < population.size(); i++) {
Chromosome prev = population.get(i - 1), cur = population.get(i);
cur.setFitnessSelection(cur.getFitnessSelection() + prev.getFitnessSelection());
}
List<Chromosome> result = new ArrayList<Chromosome>();
for(int i = 0; i < n; i++) {
| double rVal = Range.R.nextDouble() * sum;
|
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleBottom extends FitnessFunction {
public static final int GENE_BOTTOM_1 = 0;
public static final int GENE_BOTTOM_2 = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1;
private double bottom2;
private double top;
private double sellLoss;
private double sellGain;
public DoubleBottom(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleBottom extends FitnessFunction {
public static final int GENE_BOTTOM_1 = 0;
public static final int GENE_BOTTOM_2 = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1;
private double bottom2;
private double top;
private double sellLoss;
private double sellGain;
public DoubleBottom(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleBottom extends FitnessFunction {
public static final int GENE_BOTTOM_1 = 0;
public static final int GENE_BOTTOM_2 = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1;
private double bottom2;
private double top;
private double sellLoss;
private double sellGain;
public DoubleBottom(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
package ch.epfl.bigdata.ts.pattern.fitness;
public class DoubleBottom extends FitnessFunction {
public static final int GENE_BOTTOM_1 = 0;
public static final int GENE_BOTTOM_2 = 1;
public static final int GENE_PROTECT_SELL_GAIN = 2;
public static final int GENE_PROTECT_SELL_LOSS = 3;
public static final int GENE_TREND_STRENGTH = 4;
private double bottom1;
private double bottom2;
private double top;
private double sellLoss;
private double sellGain;
public DoubleBottom(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*; | return toRet;
}
protected void init() {
bottom1 = -1;
bottom2 = -1;
top = -1;
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
sellLoss = -1;
sellGain = -1;
}
private void sell() {
openPosition = false;
sell = DO_NOT_SELL;
amount += numOfShares * lastPrice;
numOfShares = 0;
bottom2 = top = -1;
sellLoss = -1;
sellGain = -1;
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/DoubleBottom.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.*;
return toRet;
}
protected void init() {
bottom1 = -1;
bottom2 = -1;
top = -1;
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
sellLoss = -1;
sellGain = -1;
}
private void sell() {
openPosition = false;
sell = DO_NOT_SELL;
amount += numOfShares * lastPrice;
numOfShares = 0;
bottom2 = top = -1;
sellLoss = -1;
sellGain = -1;
}
| public static List<Range> getGeneRanges() { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | package ch.epfl.bigdata.ts.pattern.fitness;
/**
* Created by Ena, Poly on 5/10/2014.
*/
public class HeadAndShoulders extends FitnessFunction {
public static final int GENE_BOTTOM_SHOULDER = 0;
public static final int GENE_SHOULDER_HEAD = 1;
public static final int GENE_MAX_DIFF_BOTTOMS = 2;
public static final int GENE_PROTECT_BUY_GAIN = 3;
public static final int GENE_PROTECT_BUY_LOSS = 4;
public static final int GENE_TREND_STRENGTH = 5;
private double shoulder1, shoulder2;
private double head;
private double bottom1, bottom2;
private double bottom1Ts, bottom2Ts;
private double necklinea, necklineb;
private double buyLoss;
private double buyGain;
private boolean first = true;
public HeadAndShoulders(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new HeadAndShoulders(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
package ch.epfl.bigdata.ts.pattern.fitness;
/**
* Created by Ena, Poly on 5/10/2014.
*/
public class HeadAndShoulders extends FitnessFunction {
public static final int GENE_BOTTOM_SHOULDER = 0;
public static final int GENE_SHOULDER_HEAD = 1;
public static final int GENE_MAX_DIFF_BOTTOMS = 2;
public static final int GENE_PROTECT_BUY_GAIN = 3;
public static final int GENE_PROTECT_BUY_LOSS = 4;
public static final int GENE_TREND_STRENGTH = 5;
private double shoulder1, shoulder2;
private double head;
private double bottom1, bottom2;
private double bottom1Ts, bottom2Ts;
private double necklinea, necklineb;
private double buyLoss;
private double buyGain;
private boolean first = true;
public HeadAndShoulders(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new HeadAndShoulders(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | package ch.epfl.bigdata.ts.pattern.fitness;
/**
* Created by Ena, Poly on 5/10/2014.
*/
public class HeadAndShoulders extends FitnessFunction {
public static final int GENE_BOTTOM_SHOULDER = 0;
public static final int GENE_SHOULDER_HEAD = 1;
public static final int GENE_MAX_DIFF_BOTTOMS = 2;
public static final int GENE_PROTECT_BUY_GAIN = 3;
public static final int GENE_PROTECT_BUY_LOSS = 4;
public static final int GENE_TREND_STRENGTH = 5;
private double shoulder1, shoulder2;
private double head;
private double bottom1, bottom2;
private double bottom1Ts, bottom2Ts;
private double necklinea, necklineb;
private double buyLoss;
private double buyGain;
private boolean first = true;
public HeadAndShoulders(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new HeadAndShoulders(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
package ch.epfl.bigdata.ts.pattern.fitness;
/**
* Created by Ena, Poly on 5/10/2014.
*/
public class HeadAndShoulders extends FitnessFunction {
public static final int GENE_BOTTOM_SHOULDER = 0;
public static final int GENE_SHOULDER_HEAD = 1;
public static final int GENE_MAX_DIFF_BOTTOMS = 2;
public static final int GENE_PROTECT_BUY_GAIN = 3;
public static final int GENE_PROTECT_BUY_LOSS = 4;
public static final int GENE_TREND_STRENGTH = 5;
private double shoulder1, shoulder2;
private double head;
private double bottom1, bottom2;
private double bottom1Ts, bottom2Ts;
private double necklinea, necklineb;
private double buyLoss;
private double buyGain;
private boolean first = true;
public HeadAndShoulders(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
super(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
public FitnessFunction constructorWrapper(int numOfDays, int startingAmountOfMoney, int numOfDaysInGeneration, int startForData, long time) {
return new HeadAndShoulders(numOfDays, startingAmountOfMoney, numOfDaysInGeneration, startForData, time);
}
| protected int trade(Tick transaction, Chromosome chr, boolean logForViz, StringBuilder vizLog, int order) { |
bigdata-trading/algo-trading-strategies | src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java | // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
| import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List; | }
vizLog.append("\n");
}
return toRet;
}
private void initPattern() {
shoulder1 = shoulder2 = -1;
head = -1;
bottom1 = bottom2 = -1;
}
protected void init() {
initPattern();
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
first = true;
}
private void buy() {
openPosition = false;
numOfShares = (int) Math.floor(amount / lastPrice);
amount -= numOfShares * lastPrice;
initPattern();
}
| // Path: src/ch/epfl/bigdata/ts/dataparser/Tick.java
// public class Tick implements Comparable<Tick> {
//
// long orderID;
// long timestamp;
// char type;
// long numberShares;
// double price;
//
// public long getOrderID() {
// return orderID;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public char getType() {
// return type;
// }
//
// public long getNumberShares() {
// return numberShares;
// }
//
// public double getPrice() {
// return price;
// }
//
// public Tick(long orderID, long timestamp, char type, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.type = type;
// this.numberShares = numberShares;
// this.price = price / 10000;
// }
//
// public Tick(long orderID, long timestamp, long numberShares, long price) {
// this.orderID = orderID;
// this.timestamp = timestamp;
// this.numberShares = numberShares;
// this.price = price / 10000.0;
// }
//
//
// @Override
// public int compareTo(Tick o) {
// if (this.timestamp < o.timestamp)
// return -1;
// else if (this.timestamp==o.timestamp)
// return 0;
//
// return 1;
// }
//
// @Override
// public String toString() {
// return timestamp +
// "," + type +
// "," + numberShares +
// "," + price;
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/Chromosome.java
// public class Chromosome {
//
// private List<Gene> genes; //TODO: check if HashMap of genes would be more suitable
// private double fitness = 0, fitnessSelection = 0;
// private int numberOfTransactions=0;
//
// public Chromosome(List<Gene> genes) { //TODO: organize Gene and Chromosome
// this.genes = genes;
// }
//
// public Chromosome(Chromosome chr) {
// genes = new ArrayList<Gene>();
// for(int i = 0; i < chr.genes.size(); i++) {
// genes.add(new Gene(chr.genes.get(i)));
// }
// }
//
// public double getFitness() {
// return fitness;
// }
//
// public void setFitness(double fitness) {
// this.fitness = fitness;
// }
//
// public double getFitnessSelection() {
// return fitnessSelection;
// }
//
// public void setFitnessSelection(double fitnessSelection) {
// this.fitnessSelection = fitnessSelection;
// }
//
// public int getNumGenes() {
// return genes.size();
// }
//
// public List<Gene> getGenes() {
// return genes;
// }
//
// public int getNumberOfTransactions() {
// return numberOfTransactions;
// }
//
// public void setNumberOfTransactions(int numberOfTransactions) {
// this.numberOfTransactions = numberOfTransactions;
// }
//
//
// public void copyGenes(int startPoint, int endPoint, Chromosome child) {
// for(int i = startPoint; i < endPoint; i++) {
// child.genes.add(genes.get(i));
// }
// }
//
// public void addGene(Gene gene) {
// genes.add(gene);
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < genes.size(); i++) {
// sb.append(genes.get(i));
// }
// return sb.toString();
// }
// }
//
// Path: src/ch/epfl/bigdata/ts/ga/util/Range.java
// public class Range {
// public static Random R = new Random(System.currentTimeMillis());
// private double upper, lower;
//
// public Range(double lower, double upper) {
// this.upper = upper;
// this.lower = lower;
// }
//
// public double getLower() {
// return lower;
// }
//
// public double getUpper() {
// return upper;
// }
//
// }
// Path: src/ch/epfl/bigdata/ts/pattern/fitness/HeadAndShoulders.java
import ch.epfl.bigdata.ts.dataparser.Tick;
import ch.epfl.bigdata.ts.ga.Chromosome;
import ch.epfl.bigdata.ts.ga.util.Range;
import java.util.LinkedList;
import java.util.List;
}
vizLog.append("\n");
}
return toRet;
}
private void initPattern() {
shoulder1 = shoulder2 = -1;
head = -1;
bottom1 = bottom2 = -1;
}
protected void init() {
initPattern();
openPosition = false;
lastPrice = 0;
amount = startingAmountOfMoney;
first = true;
}
private void buy() {
openPosition = false;
numOfShares = (int) Math.floor(amount / lastPrice);
amount -= numOfShares * lastPrice;
initPattern();
}
| public static List<Range> getGeneRanges() { |
sfPlayer1/Matcher | src/matcher/gui/tab/WebViewTab.java | // Path: src/matcher/gui/IGuiComponent.java
// public interface IGuiComponent {
// default void onProjectChange() { }
//
// default void onViewChange() { }
//
// default void onMappingChange() { }
// default void onMatchChange(Set<MatchType> types) { }
//
// default void onClassSelect(ClassInstance cls) { }
// default void onMethodSelect(MethodInstance method) { }
// default void onFieldSelect(FieldInstance field) { }
// default void onMethodVarSelect(MethodVarInstance arg) { }
//
// default void onMatchListRefresh() { }
// }
//
// Path: src/matcher/srcprocess/HtmlUtil.java
// public class HtmlUtil {
// public static String getId(MethodInstance method) {
// return "method-".concat(escapeId(method.getId()));
// }
//
// public static String getId(FieldInstance field) {
// return "field-".concat(escapeId(field.getId()));
// }
//
// private static String escapeId(String str) {
// StringBuilder ret = null;
// int retEnd = 0;
//
// for (int i = 0, max = str.length(); i < max; i++) {
// char c = str.charAt(i);
//
// if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' && c != '_' && c != '.') { // use : as an escape identifier
// if (ret == null) ret = new StringBuilder(max * 2);
//
// ret.append(str, retEnd, i);
//
// ret.append(':');
//
// for (int j = 0; j < 4; j++) {
// int v = (c >>> ((3 - j) * 4)) & 0xf;
// ret.append("0123456789abcdef".charAt(v));
// }
//
// retEnd = i + 1;
// }
// }
//
// if (ret == null) {
// return str;
// } else {
// ret.append(str, retEnd, str.length());
//
// return ret.toString();
// }
// }
//
// public static String escape(String str) {
// StringBuilder ret = null;
// int retEnd = 0;
//
// for (int i = 0, max = str.length(); i < max; i++) {
// char c = str.charAt(i);
//
// if (c == '<' || c == '>' || c == '&') {
// if (ret == null) ret = new StringBuilder(max * 2);
//
// ret.append(str, retEnd, i);
//
// if (c == '<') {
// ret.append("<");
// } else if (c == '>') {
// ret.append(">");
// } else {
// ret.append("&");
// }
//
// retEnd = i + 1;
// }
// }
//
// if (ret == null) {
// return str;
// } else {
// ret.append(str, retEnd, str.length());
//
// return ret.toString();
// }
// }
// }
| import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import javafx.concurrent.Worker.State;
import javafx.scene.control.Tab;
import javafx.scene.web.WebView;
import matcher.gui.IGuiComponent;
import matcher.srcprocess.HtmlUtil; | package matcher.gui.tab;
abstract class WebViewTab extends Tab implements IGuiComponent {
protected WebViewTab(String text, String templatePath) {
super(text);
this.template = readTemplate(templatePath);
webView.getEngine().getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == State.SUCCEEDED) {
Runnable r;
while ((r = pendingWebViewTasks.poll()) != null) {
r.run();
}
}
});
setContent(webView);
}
protected void displayText(String text) { | // Path: src/matcher/gui/IGuiComponent.java
// public interface IGuiComponent {
// default void onProjectChange() { }
//
// default void onViewChange() { }
//
// default void onMappingChange() { }
// default void onMatchChange(Set<MatchType> types) { }
//
// default void onClassSelect(ClassInstance cls) { }
// default void onMethodSelect(MethodInstance method) { }
// default void onFieldSelect(FieldInstance field) { }
// default void onMethodVarSelect(MethodVarInstance arg) { }
//
// default void onMatchListRefresh() { }
// }
//
// Path: src/matcher/srcprocess/HtmlUtil.java
// public class HtmlUtil {
// public static String getId(MethodInstance method) {
// return "method-".concat(escapeId(method.getId()));
// }
//
// public static String getId(FieldInstance field) {
// return "field-".concat(escapeId(field.getId()));
// }
//
// private static String escapeId(String str) {
// StringBuilder ret = null;
// int retEnd = 0;
//
// for (int i = 0, max = str.length(); i < max; i++) {
// char c = str.charAt(i);
//
// if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' && c != '_' && c != '.') { // use : as an escape identifier
// if (ret == null) ret = new StringBuilder(max * 2);
//
// ret.append(str, retEnd, i);
//
// ret.append(':');
//
// for (int j = 0; j < 4; j++) {
// int v = (c >>> ((3 - j) * 4)) & 0xf;
// ret.append("0123456789abcdef".charAt(v));
// }
//
// retEnd = i + 1;
// }
// }
//
// if (ret == null) {
// return str;
// } else {
// ret.append(str, retEnd, str.length());
//
// return ret.toString();
// }
// }
//
// public static String escape(String str) {
// StringBuilder ret = null;
// int retEnd = 0;
//
// for (int i = 0, max = str.length(); i < max; i++) {
// char c = str.charAt(i);
//
// if (c == '<' || c == '>' || c == '&') {
// if (ret == null) ret = new StringBuilder(max * 2);
//
// ret.append(str, retEnd, i);
//
// if (c == '<') {
// ret.append("<");
// } else if (c == '>') {
// ret.append(">");
// } else {
// ret.append("&");
// }
//
// retEnd = i + 1;
// }
// }
//
// if (ret == null) {
// return str;
// } else {
// ret.append(str, retEnd, str.length());
//
// return ret.toString();
// }
// }
// }
// Path: src/matcher/gui/tab/WebViewTab.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import javafx.concurrent.Worker.State;
import javafx.scene.control.Tab;
import javafx.scene.web.WebView;
import matcher.gui.IGuiComponent;
import matcher.srcprocess.HtmlUtil;
package matcher.gui.tab;
abstract class WebViewTab extends Tab implements IGuiComponent {
protected WebViewTab(String text, String templatePath) {
super(text);
this.template = readTemplate(templatePath);
webView.getEngine().getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == State.SUCCEEDED) {
Runnable r;
while ((r = pendingWebViewTasks.poll()) != null) {
r.run();
}
}
});
setContent(webView);
}
protected void displayText(String text) { | displayHtml(HtmlUtil.escape(text)); |
sfPlayer1/Matcher | src/matcher/gui/menu/LoadMappingsPane.java | // Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingField.java
// public enum MappingField {
// PLAIN("Plain", NameType.PLAIN),
// MAPPED("Mapped", NameType.MAPPED_PLAIN),
// UID("UID", NameType.UID_PLAIN),
// AUX("AUX", NameType.AUX_PLAIN),
// AUX2("AUX2", NameType.AUX2_PLAIN);
//
// MappingField(String name, NameType type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public static final MappingField[] VALUES = values();
//
// public final String name;
// public final NameType type;
// }
| import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingField; | package matcher.gui.menu;
class LoadMappingsPane extends GridPane {
LoadMappingsPane(List<String> namespaces) {
init(namespaces);
}
private void init(List<String> namespaces) { | // Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingField.java
// public enum MappingField {
// PLAIN("Plain", NameType.PLAIN),
// MAPPED("Mapped", NameType.MAPPED_PLAIN),
// UID("UID", NameType.UID_PLAIN),
// AUX("AUX", NameType.AUX_PLAIN),
// AUX2("AUX2", NameType.AUX2_PLAIN);
//
// MappingField(String name, NameType type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public static final MappingField[] VALUES = values();
//
// public final String name;
// public final NameType type;
// }
// Path: src/matcher/gui/menu/LoadMappingsPane.java
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingField;
package matcher.gui.menu;
class LoadMappingsPane extends GridPane {
LoadMappingsPane(List<String> namespaces) {
init(namespaces);
}
private void init(List<String> namespaces) { | setHgap(GuiConstants.padding); |
sfPlayer1/Matcher | src/matcher/gui/menu/LoadMappingsPane.java | // Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingField.java
// public enum MappingField {
// PLAIN("Plain", NameType.PLAIN),
// MAPPED("Mapped", NameType.MAPPED_PLAIN),
// UID("UID", NameType.UID_PLAIN),
// AUX("AUX", NameType.AUX_PLAIN),
// AUX2("AUX2", NameType.AUX2_PLAIN);
//
// MappingField(String name, NameType type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public static final MappingField[] VALUES = values();
//
// public final String name;
// public final NameType type;
// }
| import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingField; | package matcher.gui.menu;
class LoadMappingsPane extends GridPane {
LoadMappingsPane(List<String> namespaces) {
init(namespaces);
}
private void init(List<String> namespaces) {
setHgap(GuiConstants.padding);
setVgap(GuiConstants.padding);
add(new Label("Namespace"), 1, 0);
add(new Label("Field"), 2, 0);
add(new Label("Source:"), 0, 1);
cbNsSrc = new ComboBox<>(FXCollections.observableArrayList(namespaces));
cbNsSrc.getSelectionModel().select(0);
add(cbNsSrc, 1, 1); | // Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingField.java
// public enum MappingField {
// PLAIN("Plain", NameType.PLAIN),
// MAPPED("Mapped", NameType.MAPPED_PLAIN),
// UID("UID", NameType.UID_PLAIN),
// AUX("AUX", NameType.AUX_PLAIN),
// AUX2("AUX2", NameType.AUX2_PLAIN);
//
// MappingField(String name, NameType type) {
// this.name = name;
// this.type = type;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public static final MappingField[] VALUES = values();
//
// public final String name;
// public final NameType type;
// }
// Path: src/matcher/gui/menu/LoadMappingsPane.java
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingField;
package matcher.gui.menu;
class LoadMappingsPane extends GridPane {
LoadMappingsPane(List<String> namespaces) {
init(namespaces);
}
private void init(List<String> namespaces) {
setHgap(GuiConstants.padding);
setVgap(GuiConstants.padding);
add(new Label("Namespace"), 1, 0);
add(new Label("Field"), 2, 0);
add(new Label("Source:"), 0, 1);
cbNsSrc = new ComboBox<>(FXCollections.observableArrayList(namespaces));
cbNsSrc.getSelectionModel().select(0);
add(cbNsSrc, 1, 1); | cbFieldSrc = new ComboBox<>(FXCollections.observableArrayList(MappingField.VALUES)); |
sfPlayer1/Matcher | src/matcher/gui/menu/UidSetupPane.java | // Path: src/matcher/config/UidConfig.java
// public class UidConfig {
// public UidConfig() {
// this("", 0, "", "", "", "", "");
// }
//
// public UidConfig(Preferences prefs) {
// this(prefs.get("uidHost", ""),
// prefs.getInt("uidPort", 0),
// prefs.get("uidUser", ""),
// prefs.get("uidPassword", ""),
// prefs.get("uidProject", ""),
// prefs.get("uidVersionA", ""),
// prefs.get("uidVersionB", ""));
// }
//
// public UidConfig(String host, int port, String user, String password, String project, String versionA, String versionB) {
// this.host = host;
// this.port = port;
// this.user = user;
// this.password = password;
// this.project = project;
// this.versionA = versionA;
// this.versionB = versionB;
// }
//
// public InetSocketAddress getAddress() {
// if (host.isEmpty() || port <= 0) return null;
//
// return new InetSocketAddress(host, port);
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public String getToken() {
// if (user == null || password == null) return null;
//
// return user+":"+password;
// }
//
// public String getProject() {
// return project;
// }
//
// public String getVersionA() {
// return versionA;
// }
//
// public String getVersionB() {
// return versionB;
// }
//
// public boolean isValid() {
// return !host.isEmpty()
// && port > 0 && port <= 0xffff
// && !user.isEmpty()
// && !password.isEmpty()
// && !project.isEmpty()
// && !versionA.isEmpty()
// && !versionB.isEmpty();
// }
//
// void save(Preferences prefs) {
// if (!isValid()) return;
//
// if (host != null) prefs.put("uidHost", host);
// if (port != 0) prefs.putInt("uidPort", port);
// if (user != null) prefs.put("uidUser", user);
// if (password != null) prefs.put("uidPassword", password);
// if (project != null) prefs.put("uidProject", project);
// if (versionA != null) prefs.put("uidVersionA", versionA);
// if (versionB != null) prefs.put("uidVersionB", versionB);
// }
//
// private final String host;
// private final int port;
// private final String user;
// private final String password;
// private final String project;
// private final String versionA;
// private final String versionB;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
| import java.net.InetSocketAddress;
import javafx.beans.value.ChangeListener;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Window;
import matcher.config.UidConfig;
import matcher.gui.GuiConstants; | package matcher.gui.menu;
public class UidSetupPane extends GridPane {
UidSetupPane(UidConfig config, Window window, Node okButton) {
//this.window = window;
this.okButton = okButton;
init(config);
}
private void init(UidConfig config) { | // Path: src/matcher/config/UidConfig.java
// public class UidConfig {
// public UidConfig() {
// this("", 0, "", "", "", "", "");
// }
//
// public UidConfig(Preferences prefs) {
// this(prefs.get("uidHost", ""),
// prefs.getInt("uidPort", 0),
// prefs.get("uidUser", ""),
// prefs.get("uidPassword", ""),
// prefs.get("uidProject", ""),
// prefs.get("uidVersionA", ""),
// prefs.get("uidVersionB", ""));
// }
//
// public UidConfig(String host, int port, String user, String password, String project, String versionA, String versionB) {
// this.host = host;
// this.port = port;
// this.user = user;
// this.password = password;
// this.project = project;
// this.versionA = versionA;
// this.versionB = versionB;
// }
//
// public InetSocketAddress getAddress() {
// if (host.isEmpty() || port <= 0) return null;
//
// return new InetSocketAddress(host, port);
// }
//
// public String getUser() {
// return user;
// }
//
// public String getPassword() {
// return password;
// }
//
// public String getToken() {
// if (user == null || password == null) return null;
//
// return user+":"+password;
// }
//
// public String getProject() {
// return project;
// }
//
// public String getVersionA() {
// return versionA;
// }
//
// public String getVersionB() {
// return versionB;
// }
//
// public boolean isValid() {
// return !host.isEmpty()
// && port > 0 && port <= 0xffff
// && !user.isEmpty()
// && !password.isEmpty()
// && !project.isEmpty()
// && !versionA.isEmpty()
// && !versionB.isEmpty();
// }
//
// void save(Preferences prefs) {
// if (!isValid()) return;
//
// if (host != null) prefs.put("uidHost", host);
// if (port != 0) prefs.putInt("uidPort", port);
// if (user != null) prefs.put("uidUser", user);
// if (password != null) prefs.put("uidPassword", password);
// if (project != null) prefs.put("uidProject", project);
// if (versionA != null) prefs.put("uidVersionA", versionA);
// if (versionB != null) prefs.put("uidVersionB", versionB);
// }
//
// private final String host;
// private final int port;
// private final String user;
// private final String password;
// private final String project;
// private final String versionA;
// private final String versionB;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
// Path: src/matcher/gui/menu/UidSetupPane.java
import java.net.InetSocketAddress;
import javafx.beans.value.ChangeListener;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Window;
import matcher.config.UidConfig;
import matcher.gui.GuiConstants;
package matcher.gui.menu;
public class UidSetupPane extends GridPane {
UidSetupPane(UidConfig config, Window window, Node okButton) {
//this.window = window;
this.okButton = okButton;
init(config);
}
private void init(UidConfig config) { | setHgap(GuiConstants.padding); |
sfPlayer1/Matcher | src/matcher/gui/menu/FixRecordNamesPane.java | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import matcher.NameType;
import matcher.gui.GuiConstants; | package matcher.gui.menu;
class FixRecordNamesPane extends GridPane {
FixRecordNamesPane() {
init();
}
private void init() { | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
// Path: src/matcher/gui/menu/FixRecordNamesPane.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import matcher.NameType;
import matcher.gui.GuiConstants;
package matcher.gui.menu;
class FixRecordNamesPane extends GridPane {
FixRecordNamesPane() {
init();
}
private void init() { | setHgap(GuiConstants.padding); |
sfPlayer1/Matcher | src/matcher/gui/menu/FixRecordNamesPane.java | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import matcher.NameType;
import matcher.gui.GuiConstants; | package matcher.gui.menu;
class FixRecordNamesPane extends GridPane {
FixRecordNamesPane() {
init();
}
private void init() {
setHgap(GuiConstants.padding);
setVgap(GuiConstants.padding);
| // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
// Path: src/matcher/gui/menu/FixRecordNamesPane.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import matcher.NameType;
import matcher.gui.GuiConstants;
package matcher.gui.menu;
class FixRecordNamesPane extends GridPane {
FixRecordNamesPane() {
init();
}
private void init() {
setHgap(GuiConstants.padding);
setVgap(GuiConstants.padding);
| List<NameType> namespaces = new ArrayList<>(); |
sfPlayer1/Matcher | src/matcher/gui/menu/SaveMappingsPane.java | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingsExportVerbosity.java
// public enum MappingsExportVerbosity {
// MINIMAL, ROOTS, FULL;
// }
| import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.NameType;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingsExportVerbosity; | package matcher.gui.menu;
class SaveMappingsPane extends GridPane {
SaveMappingsPane(boolean offerNamespaces) {
init(offerNamespaces);
}
private void init(boolean offerNamespaces) { | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
//
// Path: src/matcher/gui/GuiConstants.java
// public class GuiConstants {
// public static final double padding = 5;
// }
//
// Path: src/matcher/mapping/MappingsExportVerbosity.java
// public enum MappingsExportVerbosity {
// MINIMAL, ROOTS, FULL;
// }
// Path: src/matcher/gui/menu/SaveMappingsPane.java
import java.util.List;
import javafx.collections.FXCollections;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import matcher.NameType;
import matcher.gui.GuiConstants;
import matcher.mapping.MappingsExportVerbosity;
package matcher.gui.menu;
class SaveMappingsPane extends GridPane {
SaveMappingsPane(boolean offerNamespaces) {
init(offerNamespaces);
}
private void init(boolean offerNamespaces) { | setHgap(GuiConstants.padding); |
sfPlayer1/Matcher | src/matcher/type/ClassEnv.java | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
| import java.util.Collection;
import matcher.NameType; | package matcher.type;
public interface ClassEnv {
boolean isShared();
Collection<ClassInstance> getClasses();
default ClassInstance getClsByName(String name) {
return getClsById(ClassInstance.getId(name));
}
ClassInstance getClsById(String id);
default ClassInstance getLocalClsByName(String name) {
return getLocalClsById(ClassInstance.getId(name));
}
ClassInstance getLocalClsById(String id);
default ClassInstance getCreateClassInstance(String id) {
return getCreateClassInstance(id, true);
}
ClassInstance getCreateClassInstance(String id, boolean createUnknown);
| // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
// Path: src/matcher/type/ClassEnv.java
import java.util.Collection;
import matcher.NameType;
package matcher.type;
public interface ClassEnv {
boolean isShared();
Collection<ClassInstance> getClasses();
default ClassInstance getClsByName(String name) {
return getClsById(ClassInstance.getId(name));
}
ClassInstance getClsById(String id);
default ClassInstance getLocalClsByName(String name) {
return getLocalClsById(ClassInstance.getId(name));
}
ClassInstance getLocalClsById(String id);
default ClassInstance getCreateClassInstance(String id) {
return getCreateClassInstance(id, true);
}
ClassInstance getCreateClassInstance(String id, boolean createUnknown);
| default ClassInstance getClsByName(String name, NameType nameType) { |
sfPlayer1/Matcher | src/matcher/type/Matchable.java | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
| import matcher.NameType; | package matcher.type;
public interface Matchable<T extends Matchable<T>> {
MatchableKind getKind();
String getId();
String getName(); | // Path: src/matcher/NameType.java
// public enum NameType {
// PLAIN(true, false, false, 0),
// MAPPED(false, true, false, 0),
// AUX(false, false, false, 1),
// AUX2(false, false, false, 2),
//
// MAPPED_PLAIN(true, true, false, 0),
// MAPPED_AUX_PLAIN(true, true, false, 1),
// MAPPED_AUX2_PLAIN(true, true, false, 2),
// MAPPED_TMP_PLAIN(true, true, true, 0),
// MAPPED_LOCTMP_PLAIN(true, true, false, 0),
//
// UID_PLAIN(true, false, false, 0),
// TMP_PLAIN(true, false, true, 0),
// LOCTMP_PLAIN(true, false, false, 0),
// AUX_PLAIN(true, false, false, 1),
// AUX2_PLAIN(true, false, false, 2);
//
// NameType(boolean plain, boolean mapped, boolean tmp, int aux) {
// this.plain = plain;
// this.mapped = mapped;
// this.tmp = tmp;
// this.aux = aux;
// }
//
// public NameType withPlain(boolean value) {
// if (plain == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_PLAIN;
//
// return VALUES[AUX_PLAIN.ordinal() + aux - 1];
// } else if (this == MAPPED_PLAIN) {
// return MAPPED;
// } else if (aux > 0 && !mapped && !tmp) {
// return VALUES[AUX.ordinal() + aux - 1];
// } else {
// throw new UnsupportedOperationException();
// }
// }
//
// public NameType withMapped(boolean value) {
// if (mapped == value) return this;
//
// if (value) {
// if (aux > 0) return VALUES[MAPPED_AUX_PLAIN.ordinal() + aux - 1];
// if (tmp) return MAPPED_TMP_PLAIN;
// if (plain) return MAPPED_PLAIN;
//
// return MAPPED;
// } else {
// if (aux > 0) return VALUES[(plain ? AUX_PLAIN : AUX).ordinal() + aux - 1];
// if (tmp) return TMP_PLAIN;
// if (this == MAPPED_LOCTMP_PLAIN) return LOCTMP_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withAux(int index, boolean value) {
// if ((aux - 1 == index) == value) return this;
//
// if (value) {
// if (mapped) return VALUES[MAPPED_AUX_PLAIN.ordinal() + index];
// if (plain) return VALUES[AUX_PLAIN.ordinal() + index];
//
// return VALUES[AUX.ordinal() + index];
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// public NameType withTmp(boolean value) {
// if (tmp == value) return this;
//
// if (value) {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// } else {
// if (mapped) return MAPPED_PLAIN;
//
// return PLAIN;
// }
// }
//
// // transform between tmp <-> loctmp
// public NameType withUnmatchedTmp(boolean value) {
// boolean locTmp = this == MAPPED_LOCTMP_PLAIN || this == LOCTMP_PLAIN;
//
// if (value == locTmp || !tmp && !locTmp) return this;
//
// if (value) {
// if (mapped) return MAPPED_LOCTMP_PLAIN;
//
// return LOCTMP_PLAIN;
// } else {
// if (mapped) return MAPPED_TMP_PLAIN;
//
// return TMP_PLAIN;
// }
// }
//
// public boolean isAux() {
// return aux > 0;
// }
//
// public int getAuxIndex() {
// if (aux == 0) throw new NoSuchElementException();
//
// return aux - 1;
// }
//
// public static NameType getAux(int index) {
// Objects.checkIndex(index, AUX_COUNT);
//
// return VALUES[NameType.AUX.ordinal() + index];
// }
//
// public static final int AUX_COUNT = 2;
//
// private static final NameType[] VALUES = values();
//
// public final boolean plain;
// public final boolean mapped;
// public final boolean tmp;
// private final int aux;
// }
// Path: src/matcher/type/Matchable.java
import matcher.NameType;
package matcher.type;
public interface Matchable<T extends Matchable<T>> {
MatchableKind getKind();
String getId();
String getName(); | String getName(NameType type); |
sfPlayer1/Matcher | src/matcher/classifier/MatchingCache.java | // Path: src/matcher/type/Matchable.java
// public interface Matchable<T extends Matchable<T>> {
// MatchableKind getKind();
//
// String getId();
// String getName();
// String getName(NameType type);
//
// default String getDisplayName(NameType type, boolean full) {
// return getName(type);
// }
//
// boolean hasMappedName();
// boolean hasLocalTmpName();
// boolean hasAuxName(int index);
//
// String getMappedComment();
// void setMappedComment(String comment);
//
// Matchable<?> getOwner();
// ClassEnv getEnv();
//
// int getUid();
//
// boolean hasPotentialMatch();
//
// boolean isMatchable();
// boolean setMatchable(boolean matchable);
//
// default boolean hasMatch() {
// return getMatch() != null;
// }
//
// T getMatch();
// boolean isFullyMatched(boolean recursive);
// float getSimilarity();
// boolean isNameObfuscated();
// }
| import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import matcher.type.Matchable; | package matcher.classifier;
public class MatchingCache {
@SuppressWarnings("unchecked") | // Path: src/matcher/type/Matchable.java
// public interface Matchable<T extends Matchable<T>> {
// MatchableKind getKind();
//
// String getId();
// String getName();
// String getName(NameType type);
//
// default String getDisplayName(NameType type, boolean full) {
// return getName(type);
// }
//
// boolean hasMappedName();
// boolean hasLocalTmpName();
// boolean hasAuxName(int index);
//
// String getMappedComment();
// void setMappedComment(String comment);
//
// Matchable<?> getOwner();
// ClassEnv getEnv();
//
// int getUid();
//
// boolean hasPotentialMatch();
//
// boolean isMatchable();
// boolean setMatchable(boolean matchable);
//
// default boolean hasMatch() {
// return getMatch() != null;
// }
//
// T getMatch();
// boolean isFullyMatched(boolean recursive);
// float getSimilarity();
// boolean isNameObfuscated();
// }
// Path: src/matcher/classifier/MatchingCache.java
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import matcher.type.Matchable;
package matcher.classifier;
public class MatchingCache {
@SuppressWarnings("unchecked") | public <T, U extends Matchable<U>> T get(CacheToken<T> token, U a, U b) { |
jenkinsci/tikal-multijob-plugin | src/test/java/com/tikal/jenkins/plugins/multijob/test/QuietPeriodCalculatorTest.java | // Path: src/main/java/com/tikal/jenkins/plugins/multijob/QuietPeriodCalculator.java
// public class QuietPeriodCalculator {
//
// private final static Logger LOG = Logger.getLogger(QuietPeriodCalculator.class.getName());
// private static final String INDEX = "index";
// private final BuildListener listener;
// private final String displayName;
//
// public QuietPeriodCalculator() {
// this(null, null);
// }
//
// QuietPeriodCalculator(final BuildListener listener, final String displayNameOrNull) {
// this.listener = listener;
// this.displayName = displayNameOrNull == null ? "" : displayNameOrNull + ": ";
// }
//
// public int calculate(String quietPeriodGroovy, int index) {
//
// if (quietPeriodGroovy == null) {
// return 0;
// }
//
// assertPositiveIndex(index);
//
// try {
// return calculateOrThrow(quietPeriodGroovy, index);
// } catch (Throwable t) {
// final String message =
// "Error calculating quiet time for index " + index + " and quietPeriodGroovy [" + quietPeriodGroovy +
// "]: " + t.getMessage() + "; returning 0";
// LOG.log(Level.WARNING, message, t);
// log(message);
// return 0;
// }
//
// }
//
// public int calculateOrThrow(final String quietPeriodGroovy, final int index) {
//
// assertPositiveIndex(index);
//
// final Integer quietPeriod = (Integer) Eval.me(INDEX, index, quietPeriodGroovy);
// log(displayName + "Quiet period groovy=[" + quietPeriodGroovy + "], index=" + index + " -> quietPeriodGroovy=" + quietPeriod);
// return quietPeriod;
// }
//
// private static void assertPositiveIndex(final int index) {
// if (index < 0) {
// throw new IllegalArgumentException("positive index expected, got " + index);
// }
// }
//
// private void log(final String s) {
// if (listener != null) {
// listener.getLogger().println(s);
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.tikal.jenkins.plugins.multijob.QuietPeriodCalculator; | package com.tikal.jenkins.plugins.multijob.test;
public class QuietPeriodCalculatorTest {
private static final String CALC = "index < 5 ? 0 : 2 * 60"; | // Path: src/main/java/com/tikal/jenkins/plugins/multijob/QuietPeriodCalculator.java
// public class QuietPeriodCalculator {
//
// private final static Logger LOG = Logger.getLogger(QuietPeriodCalculator.class.getName());
// private static final String INDEX = "index";
// private final BuildListener listener;
// private final String displayName;
//
// public QuietPeriodCalculator() {
// this(null, null);
// }
//
// QuietPeriodCalculator(final BuildListener listener, final String displayNameOrNull) {
// this.listener = listener;
// this.displayName = displayNameOrNull == null ? "" : displayNameOrNull + ": ";
// }
//
// public int calculate(String quietPeriodGroovy, int index) {
//
// if (quietPeriodGroovy == null) {
// return 0;
// }
//
// assertPositiveIndex(index);
//
// try {
// return calculateOrThrow(quietPeriodGroovy, index);
// } catch (Throwable t) {
// final String message =
// "Error calculating quiet time for index " + index + " and quietPeriodGroovy [" + quietPeriodGroovy +
// "]: " + t.getMessage() + "; returning 0";
// LOG.log(Level.WARNING, message, t);
// log(message);
// return 0;
// }
//
// }
//
// public int calculateOrThrow(final String quietPeriodGroovy, final int index) {
//
// assertPositiveIndex(index);
//
// final Integer quietPeriod = (Integer) Eval.me(INDEX, index, quietPeriodGroovy);
// log(displayName + "Quiet period groovy=[" + quietPeriodGroovy + "], index=" + index + " -> quietPeriodGroovy=" + quietPeriod);
// return quietPeriod;
// }
//
// private static void assertPositiveIndex(final int index) {
// if (index < 0) {
// throw new IllegalArgumentException("positive index expected, got " + index);
// }
// }
//
// private void log(final String s) {
// if (listener != null) {
// listener.getLogger().println(s);
// }
// }
// }
// Path: src/test/java/com/tikal/jenkins/plugins/multijob/test/QuietPeriodCalculatorTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.tikal.jenkins.plugins.multijob.QuietPeriodCalculator;
package com.tikal.jenkins.plugins.multijob.test;
public class QuietPeriodCalculatorTest {
private static final String CALC = "index < 5 ? 0 : 2 * 60"; | private final QuietPeriodCalculator calculator = new QuietPeriodCalculator(); |
jenkinsci/tikal-multijob-plugin | src/test/java/com/tikal/jenkins/plugins/multijob/test/MultiJobParametersActionTest.java | // Path: src/main/java/com/tikal/jenkins/plugins/multijob/MultiJobParametersAction.java
// @Restricted(NoExternalUse.class)
// public class MultiJobParametersAction extends ParametersAction {
//
// private List<ParameterValue> parameters;
//
// public MultiJobParametersAction(@Nonnull List<ParameterValue> parameters) {
// super(parameters);
// this.parameters = parameters;
// }
//
// public MultiJobParametersAction(ParameterValue... parameters) {
// this(Arrays.asList(parameters));
// }
//
// @Override
// public List<ParameterValue> getParameters() {
// return Collections.unmodifiableList(parameters);
// }
//
// @Override
// public ParameterValue getParameter(String name) {
// for (ParameterValue parameter : parameters) {
// if (parameter != null && parameter.getName().equals(name)) {
// return parameter;
// }
// }
//
// return null;
// }
//
// @Extension
// public static final class MultiJobParametersActionEnvironmentContributor extends EnvironmentContributor {
//
// @Override
// public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException {
// MultiJobParametersAction action = r.getAction(MultiJobParametersAction.class);
// if (action != null) {
// for (ParameterValue p : action.getParameters()) {
// envs.putIfNotNull(p.getName(), String.valueOf(p.getValue()));
// }
// }
// }
// }
// }
| import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import com.tikal.jenkins.plugins.multijob.MultiJobParametersAction;
import hudson.model.Action;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.StringParameterValue;
import java.util.Collections;
import org.junit.Assert; | /*
* The MIT License
*
* Copyright (c) 2017 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.tikal.jenkins.plugins.multijob.test;
/**
* Tests for {@link MultiJobParametersAction}
* @author Oleg Nenashev
*/
public class MultiJobParametersActionTest {
@Test
public void shouldMergeEmptyParameters() { | // Path: src/main/java/com/tikal/jenkins/plugins/multijob/MultiJobParametersAction.java
// @Restricted(NoExternalUse.class)
// public class MultiJobParametersAction extends ParametersAction {
//
// private List<ParameterValue> parameters;
//
// public MultiJobParametersAction(@Nonnull List<ParameterValue> parameters) {
// super(parameters);
// this.parameters = parameters;
// }
//
// public MultiJobParametersAction(ParameterValue... parameters) {
// this(Arrays.asList(parameters));
// }
//
// @Override
// public List<ParameterValue> getParameters() {
// return Collections.unmodifiableList(parameters);
// }
//
// @Override
// public ParameterValue getParameter(String name) {
// for (ParameterValue parameter : parameters) {
// if (parameter != null && parameter.getName().equals(name)) {
// return parameter;
// }
// }
//
// return null;
// }
//
// @Extension
// public static final class MultiJobParametersActionEnvironmentContributor extends EnvironmentContributor {
//
// @Override
// public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException {
// MultiJobParametersAction action = r.getAction(MultiJobParametersAction.class);
// if (action != null) {
// for (ParameterValue p : action.getParameters()) {
// envs.putIfNotNull(p.getName(), String.valueOf(p.getValue()));
// }
// }
// }
// }
// }
// Path: src/test/java/com/tikal/jenkins/plugins/multijob/test/MultiJobParametersActionTest.java
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import com.tikal.jenkins.plugins.multijob.MultiJobParametersAction;
import hudson.model.Action;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.StringParameterValue;
import java.util.Collections;
import org.junit.Assert;
/*
* The MIT License
*
* Copyright (c) 2017 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.tikal.jenkins.plugins.multijob.test;
/**
* Tests for {@link MultiJobParametersAction}
* @author Oleg Nenashev
*/
public class MultiJobParametersActionTest {
@Test
public void shouldMergeEmptyParameters() { | MultiJobParametersAction params = new MultiJobParametersAction(); |
jenkinsci/tikal-multijob-plugin | src/main/java/com/tikal/jenkins/plugins/multijob/views/ProjectWrapper.java | // Path: src/main/java/com/tikal/jenkins/plugins/multijob/MultiJobProject.java
// public class MultiJobProject extends Project<MultiJobProject, MultiJobBuild>
// implements TopLevelItem {
//
// private volatile boolean pollSubjobs = false;
// private volatile String resumeEnvVars = null;
//
// @SuppressWarnings("rawtypes")
// private MultiJobProject(ItemGroup parent, String name) {
// super(parent, name);
// }
//
// public MultiJobProject(Hudson parent, String name) {
// super(parent, name);
// }
//
// @Override
// protected Class<MultiJobBuild> getBuildClass() {
// return MultiJobBuild.class;
// }
//
// @Override
// public String getPronoun() {
// return AlternativeUiTextProvider.get(PRONOUN, this, getDescriptor().getDisplayName());
// }
//
// public DescriptorImpl getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Extension(ordinal = 1000)
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
//
// public static final class DescriptorImpl extends AbstractProjectDescriptor {
// public String getDisplayName() {
// return "MultiJob Project";
// }
//
// @SuppressWarnings("rawtypes")
// public MultiJobProject newInstance(ItemGroup itemGroup, String name) {
// return new MultiJobProject(itemGroup, name);
// }
// }
//
// @Override
// protected void buildDependencyGraph(DependencyGraph graph) {
// super.buildDependencyGraph(graph);
// }
//
// public boolean isTopMost() {
// return getUpstreamProjects().size() == 0;
// }
//
// public MultiJobView getView() {
// return new MultiJobView("");
// }
//
// public String getRootUrl() {
// return Jenkins.getInstance().getRootUrl();
// }
//
// @Override
// public PollingResult poll(TaskListener listener) {
// //Preserve default behavior unless specified otherwise
// if (!getPollSubjobs()) {
// return super.poll(listener);
// }
//
// PollingResult result = super.poll(listener);
// //If multijob has changes, save the effort of checking children
// if (result.hasChanges()) {
// return result;
// }
// List<AbstractProject> downProjs = getDownstreamProjects();
// PollingResult tmpResult = new PollingResult(PollingResult.Change.NONE);
// //return when we get changes to save resources
// //If we don't get changes, return the most significant result
// for (AbstractProject downProj : downProjs) {
// tmpResult = downProj.poll(listener);
// if (result.change.ordinal() < tmpResult.change.ordinal()) {
// result = tmpResult;
// if (result.hasChanges()) {
// return result;
// }
// }
// }
// return result;
// }
//
// public boolean getPollSubjobs() {
// return pollSubjobs;
// }
//
// public void setPollSubjobs(boolean poll) {
// pollSubjobs = poll;
// }
//
// public String getResumeEnvVars() {
// return resumeEnvVars;
// }
//
// public void setResumeEnvVars(String resumeEnvVars) {
// this.resumeEnvVars = resumeEnvVars;
// }
//
// public boolean getCheckResumeEnvVars() {
// return !StringUtils.isBlank(resumeEnvVars);
// }
//
// @Override
// protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
// super.submit(req, rsp);
// JSONObject json = req.getSubmittedForm();
// String k = "multijob";
// if (json.has(k)) {
// json = json.getJSONObject(k);
// k = "pollSubjobs";
// if (json.has(k)) {
// setPollSubjobs(json.optBoolean(k));
// }
// String resumeEnvVars = null;
// k = "resumeEnvVars";
// if (json.has(k)) {
// json = json.getJSONObject(k);
// if (json.has(k)) {
// resumeEnvVars = json.getString(k);
// }
// }
// setResumeEnvVars(resumeEnvVars);
// }
// }
//
// // TODO as in https://github.com/jenkinsci/maven-plugin/pull/109:
// @Override
// public boolean scheduleBuild(Cause c) {
// return super.scheduleBuild(c);
// }
// @Override
// public boolean scheduleBuild(int quietPeriod, Cause c) {
// return super.scheduleBuild(quietPeriod, c);
// }
// @Override
// public boolean scheduleBuild(int quietPeriod) {
// return super.scheduleBuild(quietPeriod);
// }
// @Override
// public boolean scheduleBuild() {
// return super.scheduleBuild();
// }
//
// }
| import hudson.model.BallColor;
import hudson.model.HealthReport;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Result;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Job;
import hudson.model.Run;
import hudson.search.SearchIndex;
import hudson.search.Search;
import hudson.security.Permission;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.acegisecurity.AccessDeniedException;
import com.tikal.jenkins.plugins.multijob.MultiJobProject; | package com.tikal.jenkins.plugins.multijob.views;
@SuppressWarnings("rawtypes")
public class ProjectWrapper extends AbstractWrapper {
| // Path: src/main/java/com/tikal/jenkins/plugins/multijob/MultiJobProject.java
// public class MultiJobProject extends Project<MultiJobProject, MultiJobBuild>
// implements TopLevelItem {
//
// private volatile boolean pollSubjobs = false;
// private volatile String resumeEnvVars = null;
//
// @SuppressWarnings("rawtypes")
// private MultiJobProject(ItemGroup parent, String name) {
// super(parent, name);
// }
//
// public MultiJobProject(Hudson parent, String name) {
// super(parent, name);
// }
//
// @Override
// protected Class<MultiJobBuild> getBuildClass() {
// return MultiJobBuild.class;
// }
//
// @Override
// public String getPronoun() {
// return AlternativeUiTextProvider.get(PRONOUN, this, getDescriptor().getDisplayName());
// }
//
// public DescriptorImpl getDescriptor() {
// return DESCRIPTOR;
// }
//
// @Extension(ordinal = 1000)
// public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
//
// public static final class DescriptorImpl extends AbstractProjectDescriptor {
// public String getDisplayName() {
// return "MultiJob Project";
// }
//
// @SuppressWarnings("rawtypes")
// public MultiJobProject newInstance(ItemGroup itemGroup, String name) {
// return new MultiJobProject(itemGroup, name);
// }
// }
//
// @Override
// protected void buildDependencyGraph(DependencyGraph graph) {
// super.buildDependencyGraph(graph);
// }
//
// public boolean isTopMost() {
// return getUpstreamProjects().size() == 0;
// }
//
// public MultiJobView getView() {
// return new MultiJobView("");
// }
//
// public String getRootUrl() {
// return Jenkins.getInstance().getRootUrl();
// }
//
// @Override
// public PollingResult poll(TaskListener listener) {
// //Preserve default behavior unless specified otherwise
// if (!getPollSubjobs()) {
// return super.poll(listener);
// }
//
// PollingResult result = super.poll(listener);
// //If multijob has changes, save the effort of checking children
// if (result.hasChanges()) {
// return result;
// }
// List<AbstractProject> downProjs = getDownstreamProjects();
// PollingResult tmpResult = new PollingResult(PollingResult.Change.NONE);
// //return when we get changes to save resources
// //If we don't get changes, return the most significant result
// for (AbstractProject downProj : downProjs) {
// tmpResult = downProj.poll(listener);
// if (result.change.ordinal() < tmpResult.change.ordinal()) {
// result = tmpResult;
// if (result.hasChanges()) {
// return result;
// }
// }
// }
// return result;
// }
//
// public boolean getPollSubjobs() {
// return pollSubjobs;
// }
//
// public void setPollSubjobs(boolean poll) {
// pollSubjobs = poll;
// }
//
// public String getResumeEnvVars() {
// return resumeEnvVars;
// }
//
// public void setResumeEnvVars(String resumeEnvVars) {
// this.resumeEnvVars = resumeEnvVars;
// }
//
// public boolean getCheckResumeEnvVars() {
// return !StringUtils.isBlank(resumeEnvVars);
// }
//
// @Override
// protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
// super.submit(req, rsp);
// JSONObject json = req.getSubmittedForm();
// String k = "multijob";
// if (json.has(k)) {
// json = json.getJSONObject(k);
// k = "pollSubjobs";
// if (json.has(k)) {
// setPollSubjobs(json.optBoolean(k));
// }
// String resumeEnvVars = null;
// k = "resumeEnvVars";
// if (json.has(k)) {
// json = json.getJSONObject(k);
// if (json.has(k)) {
// resumeEnvVars = json.getString(k);
// }
// }
// setResumeEnvVars(resumeEnvVars);
// }
// }
//
// // TODO as in https://github.com/jenkinsci/maven-plugin/pull/109:
// @Override
// public boolean scheduleBuild(Cause c) {
// return super.scheduleBuild(c);
// }
// @Override
// public boolean scheduleBuild(int quietPeriod, Cause c) {
// return super.scheduleBuild(quietPeriod, c);
// }
// @Override
// public boolean scheduleBuild(int quietPeriod) {
// return super.scheduleBuild(quietPeriod);
// }
// @Override
// public boolean scheduleBuild() {
// return super.scheduleBuild();
// }
//
// }
// Path: src/main/java/com/tikal/jenkins/plugins/multijob/views/ProjectWrapper.java
import hudson.model.BallColor;
import hudson.model.HealthReport;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Result;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.Job;
import hudson.model.Run;
import hudson.search.SearchIndex;
import hudson.search.Search;
import hudson.security.Permission;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.acegisecurity.AccessDeniedException;
import com.tikal.jenkins.plugins.multijob.MultiJobProject;
package com.tikal.jenkins.plugins.multijob.views;
@SuppressWarnings("rawtypes")
public class ProjectWrapper extends AbstractWrapper {
| final MultiJobProject multijob; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/PolicyService.java | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class PolicyService {
| // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class PolicyService {
| private final PolicyRepository policyRepository; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/PolicyService.java | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class PolicyService {
private final PolicyRepository policyRepository;
@Autowired
public PolicyService(final PolicyRepository policyRepository) {
this.policyRepository = notNull(policyRepository);
}
| // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class PolicyService {
private final PolicyRepository policyRepository;
@Autowired
public PolicyService(final PolicyRepository policyRepository) {
this.policyRepository = notNull(policyRepository);
}
| public Optional<Policy> retrievePolicy(final String filename) { |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/controllers/ProfileController.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java
// @Adapter
// public class UserAdapter {
//
// private final UserService userService;
//
// @Autowired
// public UserAdapter(final UserService userService) {
// this.userService = notNull(userService);
// }
//
// public OperationResult registerNewUser(final RegisterCredentials credentials) {
// notNull(credentials);
//
// final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(),
// credentials.getLastname(), credentials.getPassword());
// return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping!
// }
//
// public Optional<Profile> profileFor(final String username) {
// final Result<User, UserFailure> result = userService.getUserWith(username);
// return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty();
// }
//
// public Profile profileForCurrentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName);
// return new Profile(result.success());
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/Profile.java
// public class Profile {
// public String email;
// public String username;
// public String firstname;
// public String lastname;
//
// public Profile(final User user) {
// notNull(user);
// this.username = user.username;
// this.email = user.email;
// this.firstname = user.firstname;
// this.lastname = user.lastname;
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.UserAdapter;
import se.omegapoint.facepalm.client.models.Profile;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class ProfileController {
public static final String PATH = "/profile";
| // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java
// @Adapter
// public class UserAdapter {
//
// private final UserService userService;
//
// @Autowired
// public UserAdapter(final UserService userService) {
// this.userService = notNull(userService);
// }
//
// public OperationResult registerNewUser(final RegisterCredentials credentials) {
// notNull(credentials);
//
// final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(),
// credentials.getLastname(), credentials.getPassword());
// return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping!
// }
//
// public Optional<Profile> profileFor(final String username) {
// final Result<User, UserFailure> result = userService.getUserWith(username);
// return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty();
// }
//
// public Profile profileForCurrentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName);
// return new Profile(result.success());
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/Profile.java
// public class Profile {
// public String email;
// public String username;
// public String firstname;
// public String lastname;
//
// public Profile(final User user) {
// notNull(user);
// this.username = user.username;
// this.email = user.email;
// this.firstname = user.firstname;
// this.lastname = user.lastname;
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/controllers/ProfileController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.UserAdapter;
import se.omegapoint.facepalm.client.models.Profile;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class ProfileController {
public static final String PATH = "/profile";
| private final UserAdapter userAdapter; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/controllers/ProfileController.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java
// @Adapter
// public class UserAdapter {
//
// private final UserService userService;
//
// @Autowired
// public UserAdapter(final UserService userService) {
// this.userService = notNull(userService);
// }
//
// public OperationResult registerNewUser(final RegisterCredentials credentials) {
// notNull(credentials);
//
// final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(),
// credentials.getLastname(), credentials.getPassword());
// return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping!
// }
//
// public Optional<Profile> profileFor(final String username) {
// final Result<User, UserFailure> result = userService.getUserWith(username);
// return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty();
// }
//
// public Profile profileForCurrentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName);
// return new Profile(result.success());
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/Profile.java
// public class Profile {
// public String email;
// public String username;
// public String firstname;
// public String lastname;
//
// public Profile(final User user) {
// notNull(user);
// this.username = user.username;
// this.email = user.email;
// this.firstname = user.firstname;
// this.lastname = user.lastname;
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.UserAdapter;
import se.omegapoint.facepalm.client.models.Profile;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class ProfileController {
public static final String PATH = "/profile";
private final UserAdapter userAdapter;
@Autowired
public ProfileController(final UserAdapter userAdapter) {
this.userAdapter = notNull(userAdapter);
}
@RequestMapping(value = PATH)
public String profile(final @RequestParam(value = "user", required = false) String username, final Model model) {
if (username == null) { | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java
// @Adapter
// public class UserAdapter {
//
// private final UserService userService;
//
// @Autowired
// public UserAdapter(final UserService userService) {
// this.userService = notNull(userService);
// }
//
// public OperationResult registerNewUser(final RegisterCredentials credentials) {
// notNull(credentials);
//
// final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(),
// credentials.getLastname(), credentials.getPassword());
// return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping!
// }
//
// public Optional<Profile> profileFor(final String username) {
// final Result<User, UserFailure> result = userService.getUserWith(username);
// return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty();
// }
//
// public Profile profileForCurrentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName);
// return new Profile(result.success());
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/Profile.java
// public class Profile {
// public String email;
// public String username;
// public String firstname;
// public String lastname;
//
// public Profile(final User user) {
// notNull(user);
// this.username = user.username;
// this.email = user.email;
// this.firstname = user.firstname;
// this.lastname = user.lastname;
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/controllers/ProfileController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.UserAdapter;
import se.omegapoint.facepalm.client.models.Profile;
import java.util.Optional;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class ProfileController {
public static final String PATH = "/profile";
private final UserAdapter userAdapter;
@Autowired
public ProfileController(final UserAdapter userAdapter) {
this.userAdapter = notNull(userAdapter);
}
@RequestMapping(value = PATH)
public String profile(final @RequestParam(value = "user", required = false) String username, final Model model) {
if (username == null) { | final Profile profile = userAdapter.profileForCurrentUser(); |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/controllers/FriendController.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/FriendAdapter.java
// @Adapter
// public class FriendAdapter {
//
// private final FriendService friendService;
// private final UserService userService;
//
// @Autowired
// public FriendAdapter(final FriendService friendService, final UserService userService) {
// this.friendService = notNull(friendService);
// this.userService = notNull(userService);
// }
//
// public Set<Friend> friendsForCurrentUser() {
// return friendService.friendFor(currentUser())
// .stream()
// .map(i -> new Friend(i.username, i.firstname, i.lastname))
// .collect(toSet());
// }
//
// public void addFriend(final String friendUsername) {
// final Result<User, UserService.UserFailure> friend = userService.getUserWith(friendUsername);
// if (friend.isFailure()) {
// return; // TODO [dh] Should probably propogate some form of error here
// }
//
// final boolean alreadyFriends = friendService.usersAreFriends(currentUser(), friendUsername);
// if (!alreadyFriends) {
// friendService.addFriend(currentUser(), friendUsername);
// }
// }
//
// private String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.FriendAdapter;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class FriendController {
| // Path: src/main/java/se/omegapoint/facepalm/client/adapters/FriendAdapter.java
// @Adapter
// public class FriendAdapter {
//
// private final FriendService friendService;
// private final UserService userService;
//
// @Autowired
// public FriendAdapter(final FriendService friendService, final UserService userService) {
// this.friendService = notNull(friendService);
// this.userService = notNull(userService);
// }
//
// public Set<Friend> friendsForCurrentUser() {
// return friendService.friendFor(currentUser())
// .stream()
// .map(i -> new Friend(i.username, i.firstname, i.lastname))
// .collect(toSet());
// }
//
// public void addFriend(final String friendUsername) {
// final Result<User, UserService.UserFailure> friend = userService.getUserWith(friendUsername);
// if (friend.isFailure()) {
// return; // TODO [dh] Should probably propogate some form of error here
// }
//
// final boolean alreadyFriends = friendService.usersAreFriends(currentUser(), friendUsername);
// if (!alreadyFriends) {
// friendService.addFriend(currentUser(), friendUsername);
// }
// }
//
// private String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/controllers/FriendController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.FriendAdapter;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class FriendController {
| private final FriendAdapter friendAdapter; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
| import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5; | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5; | private final EventService eventService; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
| import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5;
private final EventService eventService;
@Autowired
public FilePolicyRepository(final EventService eventService) {
this.eventService = notNull(eventService);
}
@Override | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5;
private final EventService eventService;
@Autowired
public FilePolicyRepository(final EventService eventService) {
this.eventService = notNull(eventService);
}
@Override | public Optional<Policy> retrievePolicyWith(final String filename) { |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
| import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5;
private final EventService eventService;
@Autowired
public FilePolicyRepository(final EventService eventService) {
this.eventService = notNull(eventService);
}
@Override
public Optional<Policy> retrievePolicyWith(final String filename) {
notBlank(filename);
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final Command command = commandBasedOnOperatingSystem(filename);
final Future<String> future = executorService.submit(command);
try { | // Path: src/main/java/se/omegapoint/facepalm/domain/Policy.java
// public class Policy {
// public final String text;
//
// public Policy(final String text) {
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/PolicyRepository.java
// public interface PolicyRepository {
// Optional<Policy> retrievePolicyWith(String filename);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java
// public class GenericEvent implements ApplicationEvent {
// private final Object data;
//
// public GenericEvent(final Object data) {
// this.data = notNull(data);
// }
//
// @Override
// public String message() {
// return data.toString();
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final GenericEvent that = (GenericEvent) o;
// return Objects.equals(data, that.data);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(data);
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/FilePolicyRepository.java
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static java.lang.String.format;
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import se.omegapoint.facepalm.domain.Policy;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.PolicyRepository;
import se.omegapoint.facepalm.infrastructure.event.GenericEvent;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
public class FilePolicyRepository implements PolicyRepository {
private static final int TIMEOUT = 5;
private final EventService eventService;
@Autowired
public FilePolicyRepository(final EventService eventService) {
this.eventService = notNull(eventService);
}
@Override
public Optional<Policy> retrievePolicyWith(final String filename) {
notBlank(filename);
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final Command command = commandBasedOnOperatingSystem(filename);
final Future<String> future = executorService.submit(command);
try { | eventService.publish(new GenericEvent(format("About to execute command[%s]", command.command))); |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/config/Bootstrapper.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// @Adapter
// public class ImageAdapter {
//
// private final ImageService imageService;
//
// @Autowired
// public ImageAdapter(final ImageService imageService) {
// this.imageService = notNull(imageService);
// }
//
//
// public List<ImagePost> getTopImagePosts() {
// return imageService.getTopImages().stream()
// .map(this::imagePost)
// .collect(toList());
// }
//
// public Optional<ImagePost> getImage(final String id) {
// notBlank(id);
//
// return imageService.getImagePost(id).map(this::imagePost);
// }
//
// public List<ImageComment> getCommentsForImage(final Long imageId) {
// notNull(imageId);
//
// return imageService.getCommentsForImage(imageId).stream()
// .map(c -> new ImageComment(c.author, c.text))
// .collect(toList());
// }
//
// public void addComment(final String imageId, final String text) {
// notBlank(imageId);
// notBlank(text);
//
// imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text));
// }
//
// public void addImage(final ImageUpload imageUpload) {
// notNull(imageUpload);
// imageService.addImagePost(new Title(imageUpload.title), imageUpload.data);
// }
//
// public Image fetchImage(final Long id) {
// notNull(id);
// return imageService.getImageFor(id);
// }
//
// public String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
//
// private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) {
// return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java
// public class ImageUpload {
// public final String title;
// public final byte[] data;
//
// public ImageUpload(final String title, final byte[] data) {
// this.title = notBlank(title);
// this.data = notNull(data);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.client.adapters.ImageAdapter;
import se.omegapoint.facepalm.client.models.ImageUpload;
import java.io.BufferedInputStream;
import java.io.File; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
/**
* This class bootstraps some data which cannot be easily added via import.sql
*/
@Service
public class Bootstrapper implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class);
| // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// @Adapter
// public class ImageAdapter {
//
// private final ImageService imageService;
//
// @Autowired
// public ImageAdapter(final ImageService imageService) {
// this.imageService = notNull(imageService);
// }
//
//
// public List<ImagePost> getTopImagePosts() {
// return imageService.getTopImages().stream()
// .map(this::imagePost)
// .collect(toList());
// }
//
// public Optional<ImagePost> getImage(final String id) {
// notBlank(id);
//
// return imageService.getImagePost(id).map(this::imagePost);
// }
//
// public List<ImageComment> getCommentsForImage(final Long imageId) {
// notNull(imageId);
//
// return imageService.getCommentsForImage(imageId).stream()
// .map(c -> new ImageComment(c.author, c.text))
// .collect(toList());
// }
//
// public void addComment(final String imageId, final String text) {
// notBlank(imageId);
// notBlank(text);
//
// imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text));
// }
//
// public void addImage(final ImageUpload imageUpload) {
// notNull(imageUpload);
// imageService.addImagePost(new Title(imageUpload.title), imageUpload.data);
// }
//
// public Image fetchImage(final Long id) {
// notNull(id);
// return imageService.getImageFor(id);
// }
//
// public String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
//
// private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) {
// return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java
// public class ImageUpload {
// public final String title;
// public final byte[] data;
//
// public ImageUpload(final String title, final byte[] data) {
// this.title = notBlank(title);
// this.data = notNull(data);
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/config/Bootstrapper.java
import java.io.IOException;
import java.io.InputStream;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.client.adapters.ImageAdapter;
import se.omegapoint.facepalm.client.models.ImageUpload;
import java.io.BufferedInputStream;
import java.io.File;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
/**
* This class bootstraps some data which cannot be easily added via import.sql
*/
@Service
public class Bootstrapper implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class);
| private final ImageAdapter imageAdapter; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/config/Bootstrapper.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// @Adapter
// public class ImageAdapter {
//
// private final ImageService imageService;
//
// @Autowired
// public ImageAdapter(final ImageService imageService) {
// this.imageService = notNull(imageService);
// }
//
//
// public List<ImagePost> getTopImagePosts() {
// return imageService.getTopImages().stream()
// .map(this::imagePost)
// .collect(toList());
// }
//
// public Optional<ImagePost> getImage(final String id) {
// notBlank(id);
//
// return imageService.getImagePost(id).map(this::imagePost);
// }
//
// public List<ImageComment> getCommentsForImage(final Long imageId) {
// notNull(imageId);
//
// return imageService.getCommentsForImage(imageId).stream()
// .map(c -> new ImageComment(c.author, c.text))
// .collect(toList());
// }
//
// public void addComment(final String imageId, final String text) {
// notBlank(imageId);
// notBlank(text);
//
// imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text));
// }
//
// public void addImage(final ImageUpload imageUpload) {
// notNull(imageUpload);
// imageService.addImagePost(new Title(imageUpload.title), imageUpload.data);
// }
//
// public Image fetchImage(final Long id) {
// notNull(id);
// return imageService.getImageFor(id);
// }
//
// public String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
//
// private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) {
// return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java
// public class ImageUpload {
// public final String title;
// public final byte[] data;
//
// public ImageUpload(final String title, final byte[] data) {
// this.title = notBlank(title);
// this.data = notNull(data);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.client.adapters.ImageAdapter;
import se.omegapoint.facepalm.client.models.ImageUpload;
import java.io.BufferedInputStream;
import java.io.File; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
/**
* This class bootstraps some data which cannot be easily added via import.sql
*/
@Service
public class Bootstrapper implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class);
private final ImageAdapter imageAdapter;
private final Environment env;
@Autowired
public Bootstrapper(final ImageAdapter imageAdapter, final Environment env) {
this.imageAdapter = notNull(imageAdapter);
this.env = notNull(env);
}
@Override
@Transactional
public void afterPropertiesSet() throws Exception {
if (Boolean.valueOf(env.getProperty("bootstrap.data"))) {
LOGGER.debug("Started bootstrapping of image posts");
uploadImageFileWithTitle("He is right behind me, isn't he?", "samples/a.jpg");
uploadImageFileWithTitle("I cant believe it doesn't work this way", "samples/b.jpg");
uploadImageFileWithTitle("Mhmm.. pie", "samples/c.jpg");
LOGGER.debug("Done with bootstrapping");
}
createDocumentsIfNotPresent();
}
private void uploadImageFileWithTitle(final String title, final String filePath) {
try {
final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// @Adapter
// public class ImageAdapter {
//
// private final ImageService imageService;
//
// @Autowired
// public ImageAdapter(final ImageService imageService) {
// this.imageService = notNull(imageService);
// }
//
//
// public List<ImagePost> getTopImagePosts() {
// return imageService.getTopImages().stream()
// .map(this::imagePost)
// .collect(toList());
// }
//
// public Optional<ImagePost> getImage(final String id) {
// notBlank(id);
//
// return imageService.getImagePost(id).map(this::imagePost);
// }
//
// public List<ImageComment> getCommentsForImage(final Long imageId) {
// notNull(imageId);
//
// return imageService.getCommentsForImage(imageId).stream()
// .map(c -> new ImageComment(c.author, c.text))
// .collect(toList());
// }
//
// public void addComment(final String imageId, final String text) {
// notBlank(imageId);
// notBlank(text);
//
// imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text));
// }
//
// public void addImage(final ImageUpload imageUpload) {
// notNull(imageUpload);
// imageService.addImagePost(new Title(imageUpload.title), imageUpload.data);
// }
//
// public Image fetchImage(final Long id) {
// notNull(id);
// return imageService.getImageFor(id);
// }
//
// public String currentUser() {
// final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// return authenticatedUser.userName;
// }
//
// private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) {
// return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java
// public class ImageUpload {
// public final String title;
// public final byte[] data;
//
// public ImageUpload(final String title, final byte[] data) {
// this.title = notBlank(title);
// this.data = notNull(data);
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/config/Bootstrapper.java
import java.io.IOException;
import java.io.InputStream;
import static org.apache.commons.lang3.Validate.notNull;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.client.adapters.ImageAdapter;
import se.omegapoint.facepalm.client.models.ImageUpload;
import java.io.BufferedInputStream;
import java.io.File;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
/**
* This class bootstraps some data which cannot be easily added via import.sql
*/
@Service
public class Bootstrapper implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrapper.class);
private final ImageAdapter imageAdapter;
private final Environment env;
@Autowired
public Bootstrapper(final ImageAdapter imageAdapter, final Environment env) {
this.imageAdapter = notNull(imageAdapter);
this.env = notNull(env);
}
@Override
@Transactional
public void afterPropertiesSet() throws Exception {
if (Boolean.valueOf(env.getProperty("bootstrap.data"))) {
LOGGER.debug("Started bootstrapping of image posts");
uploadImageFileWithTitle("He is right behind me, isn't he?", "samples/a.jpg");
uploadImageFileWithTitle("I cant believe it doesn't work this way", "samples/b.jpg");
uploadImageFileWithTitle("Mhmm.. pie", "samples/c.jpg");
LOGGER.debug("Done with bootstrapping");
}
createDocumentsIfNotPresent();
}
private void uploadImageFileWithTitle(final String title, final String filePath) {
try {
final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); | imageAdapter.addImage(new ImageUpload(title, IOUtils.toByteArray(new BufferedInputStream(is)))); |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/infrastructure/JPADocumentRepository.java | // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java
// public interface DocumentRepository {
// List<Document> findAllFor(String user);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Document.java
// @Entity
// @Table(name = "DOCUMENTS")
// public class Document {
//
// @Id
// @GeneratedValue
// @Column(name = "ID")
// private Long id;
//
// @Column(name = "FILENAME")
// private String filename;
//
// @Column(name = "USERNAME")
// private String username;
//
// @Column(name = "UPLOADED_DATE")
// private Date date;
//
// @Column(name = "FILE_SIZE")
// private Long fileSize;
//
// public Long getId() {
// return id;
// }
//
// public void setId(final Long id) {
// this.id = id;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public void setFilename(final String filename) {
// this.filename = filename;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(final String username) {
// this.username = username;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(final Date date) {
// this.date = date;
// }
//
// public Long getFileSize() {
// return fileSize;
// }
//
// public void setFileSize(final Long fileSize) {
// this.fileSize = fileSize;
// }
// }
| import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.domain.repository.DocumentRepository;
import se.omegapoint.facepalm.infrastructure.db.Document;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDateTime;
import java.util.List;
import static java.lang.String.format;
import static java.time.ZoneId.systemDefault;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
@Transactional
@SuppressWarnings("unchecked") | // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java
// public interface DocumentRepository {
// List<Document> findAllFor(String user);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Document.java
// @Entity
// @Table(name = "DOCUMENTS")
// public class Document {
//
// @Id
// @GeneratedValue
// @Column(name = "ID")
// private Long id;
//
// @Column(name = "FILENAME")
// private String filename;
//
// @Column(name = "USERNAME")
// private String username;
//
// @Column(name = "UPLOADED_DATE")
// private Date date;
//
// @Column(name = "FILE_SIZE")
// private Long fileSize;
//
// public Long getId() {
// return id;
// }
//
// public void setId(final Long id) {
// this.id = id;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public void setFilename(final String filename) {
// this.filename = filename;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(final String username) {
// this.username = username;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(final Date date) {
// this.date = date;
// }
//
// public Long getFileSize() {
// return fileSize;
// }
//
// public void setFileSize(final Long fileSize) {
// this.fileSize = fileSize;
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPADocumentRepository.java
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.domain.repository.DocumentRepository;
import se.omegapoint.facepalm.infrastructure.db.Document;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDateTime;
import java.util.List;
import static java.lang.String.format;
import static java.time.ZoneId.systemDefault;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
@Transactional
@SuppressWarnings("unchecked") | public class JPADocumentRepository implements DocumentRepository { |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/infrastructure/JPADocumentRepository.java | // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java
// public interface DocumentRepository {
// List<Document> findAllFor(String user);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Document.java
// @Entity
// @Table(name = "DOCUMENTS")
// public class Document {
//
// @Id
// @GeneratedValue
// @Column(name = "ID")
// private Long id;
//
// @Column(name = "FILENAME")
// private String filename;
//
// @Column(name = "USERNAME")
// private String username;
//
// @Column(name = "UPLOADED_DATE")
// private Date date;
//
// @Column(name = "FILE_SIZE")
// private Long fileSize;
//
// public Long getId() {
// return id;
// }
//
// public void setId(final Long id) {
// this.id = id;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public void setFilename(final String filename) {
// this.filename = filename;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(final String username) {
// this.username = username;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(final Date date) {
// this.date = date;
// }
//
// public Long getFileSize() {
// return fileSize;
// }
//
// public void setFileSize(final Long fileSize) {
// this.fileSize = fileSize;
// }
// }
| import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.domain.repository.DocumentRepository;
import se.omegapoint.facepalm.infrastructure.db.Document;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDateTime;
import java.util.List;
import static java.lang.String.format;
import static java.time.ZoneId.systemDefault;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
@Transactional
@SuppressWarnings("unchecked")
public class JPADocumentRepository implements DocumentRepository {
@PersistenceContext
private EntityManager entityManager;
@Override | // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java
// public interface DocumentRepository {
// List<Document> findAllFor(String user);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Document.java
// @Entity
// @Table(name = "DOCUMENTS")
// public class Document {
//
// @Id
// @GeneratedValue
// @Column(name = "ID")
// private Long id;
//
// @Column(name = "FILENAME")
// private String filename;
//
// @Column(name = "USERNAME")
// private String username;
//
// @Column(name = "UPLOADED_DATE")
// private Date date;
//
// @Column(name = "FILE_SIZE")
// private Long fileSize;
//
// public Long getId() {
// return id;
// }
//
// public void setId(final Long id) {
// this.id = id;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public void setFilename(final String filename) {
// this.filename = filename;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(final String username) {
// this.username = username;
// }
//
// public Date getDate() {
// return date;
// }
//
// public void setDate(final Date date) {
// this.date = date;
// }
//
// public Long getFileSize() {
// return fileSize;
// }
//
// public void setFileSize(final Long fileSize) {
// this.fileSize = fileSize;
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPADocumentRepository.java
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import se.omegapoint.facepalm.domain.repository.DocumentRepository;
import se.omegapoint.facepalm.infrastructure.db.Document;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.time.LocalDateTime;
import java.util.List;
import static java.lang.String.format;
import static java.time.ZoneId.systemDefault;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.infrastructure;
@Repository
@Transactional
@SuppressWarnings("unchecked")
public class JPADocumentRepository implements DocumentRepository {
@PersistenceContext
private EntityManager entityManager;
@Override | public List<se.omegapoint.facepalm.domain.Document> findAllFor(final String user) { |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
// Path: src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired | UserRepository userRepository; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserRepository userRepository;
@Autowired | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
// Path: src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserRepository userRepository;
@Autowired | EventService eventService; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserRepository userRepository;
@Autowired
EventService eventService;
@Override
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access?error")
.and().headers().xssProtection().block(false).xssProtectionEnabled(false).and() // Default setting for Spring Boot to activate XSS Protection (dont fix!)
.and().csrf().disable(); // FIXME [dh] Enabling CSRF prevents file upload, must be fixed
}
@Override
public void configure(final AuthenticationManagerBuilder managerBuilder) throws Exception { | // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// public class DbAuthenticationProvider implements AuthenticationProvider {
//
// private final UserRepository userRepository;
//
// public DbAuthenticationProvider(final UserRepository userRepository) {
// this.userRepository = notNull(userRepository);
// }
//
// @Override
// public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
// final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
// final String username = (String) token.getPrincipal();
// final String password = (String) token.getCredentials();
//
// final Optional<User> user = userRepository.findByNameAndPassword(username, password);
//
// return user.map(u -> new UsernamePasswordAuthenticationToken(new AuthenticatedUser(u.username), null, emptyList()))
// .orElse(null);
// }
//
// @Override
// public boolean supports(final Class<?> authentication) {
// return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java
// public interface EventService {
// void publish(ApplicationEvent event);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// public interface UserRepository {
// Optional<User> findByUsername(final String username);
//
// Set<User> findFriendsFor(String username);
//
// Optional<User> findByNameAndPassword(final String username, final String password);
//
// List<User> findLike(String value);
//
// void addFriend(String user, String friend);
//
// void addUser(NewUserCredentials credentials);
//
// boolean usersAreFriends(String userA, String userB);
// }
// Path: src/main/java/se/omegapoint/facepalm/client/config/SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import se.omegapoint.facepalm.client.security.DbAuthenticationProvider;
import se.omegapoint.facepalm.domain.event.EventService;
import se.omegapoint.facepalm.domain.repository.UserRepository;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.config;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserRepository userRepository;
@Autowired
EventService eventService;
@Override
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access?error")
.and().headers().xssProtection().block(false).xssProtectionEnabled(false).and() // Default setting for Spring Boot to activate XSS Protection (dont fix!)
.and().csrf().disable(); // FIXME [dh] Enabling CSRF prevents file upload, must be fixed
}
@Override
public void configure(final AuthenticationManagerBuilder managerBuilder) throws Exception { | managerBuilder.authenticationProvider(new DbAuthenticationProvider(userRepository)); |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/client/controllers/DocumentController.java | // Path: src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java
// @Adapter
// public class DocumentAdapter {
// private DocumentService documentService;
//
// @Autowired
// public DocumentAdapter(final DocumentService documentService) {
// this.documentService = notNull(documentService);
// }
//
// public List<Document> documentsFor(final String user) {
// notBlank(user);
//
// return documentService.documentsForUser(user).stream()
// .map(d -> new Document(d.filename, d.fileSize, date(d.uploadedDate)))
// .collect(toList());
// }
//
// private String date(final LocalDateTime uploadedDate) {
// return uploadedDate != null ? uploadedDate.format(DateTimeFormatter.BASIC_ISO_DATE) : "";
// }
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.DocumentAdapter;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.Validate.notNull; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class DocumentController {
| // Path: src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java
// @Adapter
// public class DocumentAdapter {
// private DocumentService documentService;
//
// @Autowired
// public DocumentAdapter(final DocumentService documentService) {
// this.documentService = notNull(documentService);
// }
//
// public List<Document> documentsFor(final String user) {
// notBlank(user);
//
// return documentService.documentsForUser(user).stream()
// .map(d -> new Document(d.filename, d.fileSize, date(d.uploadedDate)))
// .collect(toList());
// }
//
// private String date(final LocalDateTime uploadedDate) {
// return uploadedDate != null ? uploadedDate.format(DateTimeFormatter.BASIC_ISO_DATE) : "";
// }
// }
// Path: src/main/java/se/omegapoint/facepalm/client/controllers/DocumentController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import se.omegapoint.facepalm.client.adapters.DocumentAdapter;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.Validate.notNull;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.client.controllers;
@Controller
public class DocumentController {
| private final DocumentAdapter documentAdapter; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/ImageService.java | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
| import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired | private ImageRepository imageRepository; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/ImageService.java | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
| import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired | private CommentRepository commentRepository; |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/ImageService.java | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
| import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired
private CommentRepository commentRepository;
| // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired
private CommentRepository commentRepository;
| public List<ImagePost> getTopImages() { |
Omegapoint/facepalm | src/main/java/se/omegapoint/facepalm/application/ImageService.java | // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
| import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList; | /*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired
private CommentRepository commentRepository;
public List<ImagePost> getTopImages() {
return imageRepository.findAll();
}
public Optional<ImagePost> getImagePost(final String id) {
notBlank(id);
return imageRepository.findById(id);
}
| // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java
// public class NewImageComment {
// public final Long imageId;
// public final String author;
// public final String text;
//
// public NewImageComment(final Long imageId, final String author, final String text) {
// this.imageId = notNull(imageId);
// this.author = notBlank(author);
// this.text = notBlank(text);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java
// public class Image {
// public final byte[] data;
//
// public Image(final byte[] data) {
// this.data = notNull(data);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java
// public class ImageComment {
//
// public final Long imageId;
// public final String author;
// public final String text;
//
// public ImageComment(final Long imageId, final String author, final String text) {
// this.imageId = imageId;
// this.author = author;
// this.text = text;
// }
//
// @Override
// public String toString() {
// return "ImageComment{" +
// "imageId=" + imageId +
// ", author='" + author + '\'' +
// ", text='" + text + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java
// public class ImagePost {
// public final Long id;
// public final Title title;
// public final NumberOfPoints numPoints;
// public final NumberOfComments numComments;
//
// public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) {
// this.id = notNull(id);
// this.title = notNull(title);
// this.numPoints = notNull(points);
// this.numComments = notNull(numComments);
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java
// public class Title {
// private static final int MAN_LENGTH = 100;
//
// public final String value;
//
// public Title(final String value) {
// this.value = notBlank(value);
// isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters");
// }
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java
// public interface CommentRepository {
// List<ImageComment> findByImageId(final Long id);
//
// void addComment(Long imageId, String author, String text);
// }
//
// Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// public interface ImageRepository {
// List<ImagePost> findAll();
//
// Optional<ImagePost> findById(String id);
//
// void addImagePost(Title title, byte[] data);
//
// Image findImageByPostId(Long id);
// }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java
import static org.apache.commons.lang3.Validate.notBlank;
import static org.apache.commons.lang3.Validate.notNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.omegapoint.facepalm.application.transfer.NewImageComment;
import se.omegapoint.facepalm.domain.Image;
import se.omegapoint.facepalm.domain.ImageComment;
import se.omegapoint.facepalm.domain.ImagePost;
import se.omegapoint.facepalm.domain.Title;
import se.omegapoint.facepalm.domain.repository.CommentRepository;
import se.omegapoint.facepalm.domain.repository.ImageRepository;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
/*
* Copyright 2016 the original author or authors.
*
* 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 se.omegapoint.facepalm.application;
@Service
public class ImageService {
@Autowired
private ImageRepository imageRepository;
@Autowired
private CommentRepository commentRepository;
public List<ImagePost> getTopImages() {
return imageRepository.findAll();
}
public Optional<ImagePost> getImagePost(final String id) {
notBlank(id);
return imageRepository.findById(id);
}
| public List<ImageComment> getCommentsForImage(final Long id) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.