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 |
|---|---|---|---|---|---|---|
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/StargazersContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
public class StargazersContract {
public static final String LOG_TAG = StargazersContract.class.getSimpleName();
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_STARGAZERS = "stargazers";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class Entry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_STARGAZERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STARGAZERS;
public static final String TABLE_NAME = "stargazers";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String[] STARTGAZERS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_TIMESTAMP = 2;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/StargazersContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
public class StargazersContract {
public static final String LOG_TAG = StargazersContract.class.getSimpleName();
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_STARGAZERS = "stargazers";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class Entry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_STARGAZERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STARGAZERS;
public static final String TABLE_NAME = "stargazers";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String[] STARTGAZERS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_TIMESTAMP = 2;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, | Star star) { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/StargazersContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
public class StargazersContract {
public static final String LOG_TAG = StargazersContract.class.getSimpleName();
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_STARGAZERS = "stargazers";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class Entry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_STARGAZERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STARGAZERS;
public static final String TABLE_NAME = "stargazers";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String[] STARTGAZERS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_TIMESTAMP = 2;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId,
Star star) {
String timestamp = star.getStarredAt(); | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/StargazersContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.data.source.local.contract;
public class StargazersContract {
public static final String LOG_TAG = StargazersContract.class.getSimpleName();
public static final String CONTENT_AUTHORITY = "com.dmitrymalkovich.android.githubanalytics.data";
public static final String PATH_STARGAZERS = "stargazers";
private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final class Entry implements BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_STARGAZERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_STARGAZERS;
public static final String TABLE_NAME = "stargazers";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String[] STARTGAZERS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_TIMESTAMP = 2;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId,
Star star) {
String timestamp = star.getStarredAt(); | long timeInMilliseconds = TimeConverter.iso8601ToMilliseconds(timestamp); |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/AuthenticationBuilder.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
| import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import java.io.IOException;
import retrofit2.Call; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class AuthenticationBuilder extends Service{
private String mCode;
public AuthenticationBuilder setCode(String code) {
mCode = code;
return this;
}
@WorkerThread | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/AccessToken.java
// @SuppressWarnings("all")
// public class AccessToken {
//
// @SerializedName("access_token")
// private String mAccessToken;
// @SerializedName("token_type")
// private String mTokenType;
//
// public String getToken() {
// return mAccessToken;
// }
//
// public String getTokenType() {
// return mTokenType;
// }
//
// public void setTokenType(String tokenType) {
// this.mTokenType = tokenType;
// }
//
// public void setAccessToken(String accessToken) {
// this.mAccessToken = accessToken;
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/AuthenticationBuilder.java
import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.data.AccessToken;
import java.io.IOException;
import retrofit2.Call;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class AuthenticationBuilder extends Service{
private String mCode;
public AuthenticationBuilder setCode(String code) {
mCode = code;
return this;
}
@WorkerThread | public AccessToken requestAccessToken() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class TrafficService extends Service {
private String mLogin;
private String mRepositoryName;
private String mPeriod;
public TrafficService setToken(String token) {
return (TrafficService) super.setToken(token);
}
public TrafficService setTokenType(String tokenType) {
return (TrafficService) super.setTokenType(tokenType);
}
public TrafficService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public TrafficService setPeriod(String period) {
mPeriod = period;
return this;
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java
import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class TrafficService extends Service {
private String mLogin;
private String mRepositoryName;
private String mPeriod;
public TrafficService setToken(String token) {
return (TrafficService) super.setToken(token);
}
public TrafficService setTokenType(String tokenType) {
return (TrafficService) super.setTokenType(tokenType);
}
public TrafficService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public TrafficService setPeriod(String period) {
mPeriod = period;
return this;
}
| public Clones getClones() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; |
public TrafficService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public TrafficService setPeriod(String period) {
mPeriod = period;
return this;
}
public Clones getClones() throws IOException {
Call<Clones> call = createGithubService().getRepositoryClones(
mLogin, mRepositoryName, mPeriod);
Response<Clones> response = call.execute();
if (response.isSuccessful()) {
Clones clones = response.body();
if (clones != null && clones.asList() != null) {
return clones;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java
import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
public TrafficService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public TrafficService setPeriod(String period) {
mPeriod = period;
return this;
}
public Clones getClones() throws IOException {
Call<Clones> call = createGithubService().getRepositoryClones(
mLogin, mRepositoryName, mPeriod);
Response<Clones> response = call.execute();
if (response.isSuccessful()) {
Clones clones = response.body();
if (clones != null && clones.asList() != null) {
return clones;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
| public List<ReferringSite> getReferringSites() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | if (response.isSuccessful()) {
Clones clones = response.body();
if (clones != null && clones.asList() != null) {
return clones;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
public List<ReferringSite> getReferringSites() throws IOException {
Call<List<ReferringSite>> call = createGithubService().getTopReferrers(
mLogin, mRepositoryName);
Response<List<ReferringSite>> response = call.execute();
if (response.isSuccessful()) {
List<ReferringSite> referringSites = response.body();
if (referringSites != null) {
return referringSites;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Clones.java
// @SuppressWarnings("all")
// public class Clones {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("clones")
// private List<Clone> mClones;
//
// public List<Clone> asList() {
// return mClones;
// }
//
// public static class Clone {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/ReferringSite.java
// @SuppressWarnings("all")
// public class ReferringSite {
//
// @SerializedName("referrer")
// private String mReferrer;
//
// @SerializedName("count")
// private int mCount;
//
// @SerializedName("uniques")
// private int mUniques;
//
// public String getReferrer() {
// return mReferrer;
// }
//
// public int getCount() {
// return mCount;
// }
//
// public int getUniques() {
// return mUniques;
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/TrafficService.java
import com.dmitrymalkovich.android.githubapi.core.data.Clones;
import com.dmitrymalkovich.android.githubapi.core.data.ReferringSite;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
if (response.isSuccessful()) {
Clones clones = response.body();
if (clones != null && clones.asList() != null) {
return clones;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
public List<ReferringSite> getReferringSites() throws IOException {
Call<List<ReferringSite>> call = createGithubService().getTopReferrers(
mLogin, mRepositoryName);
Response<List<ReferringSite>> response = call.execute();
if (response.isSuccessful()) {
List<ReferringSite> referringSites = response.body();
if (referringSites != null) {
return referringSites;
} else {
throw new IOException();
}
} else {
APIError error = APIError.parseError(response);
throw new IOException(error.getMessage());
}
}
| public Views getViews() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/StargazersService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class StargazersService extends Service {
private String mLogin;
private String mRepositoryName;
private String mPage;
private long mDate;
public StargazersService setToken(String token) {
return (StargazersService) super.setToken(token);
}
public StargazersService setTokenType(String tokenType) {
return (StargazersService) super.setTokenType(tokenType);
}
public StargazersService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public StargazersService setPage(String page) {
mPage = page;
return this;
}
public StargazersService setDate(long date) {
mDate = date;
return this;
}
@WorkerThread | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/StargazersService.java
import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubapi.core;
public class StargazersService extends Service {
private String mLogin;
private String mRepositoryName;
private String mPage;
private long mDate;
public StargazersService setToken(String token) {
return (StargazersService) super.setToken(token);
}
public StargazersService setTokenType(String tokenType) {
return (StargazersService) super.setTokenType(tokenType);
}
public StargazersService setRepository(Repository repository) {
mRepositoryName = repository.getName();
mLogin = repository.getOwner().getLogin();
return this;
}
public StargazersService setPage(String page) {
mPage = page;
return this;
}
public StargazersService setDate(long date) {
mDate = date;
return this;
}
@WorkerThread | public List<Star> getStars() throws IOException { |
DmitryMalkovich/gito-github-client | github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/StargazersService.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
| import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | return this;
}
public StargazersService setDate(long date) {
mDate = date;
return this;
}
@WorkerThread
public List<Star> getStars() throws IOException {
Call<List<Star>> dummyCall = createGithubService().getStargazers(
mLogin, mRepositoryName, mPage);
Response<List<Star>> paginationResponse = dummyCall.execute();
if (paginationResponse.isSuccessful()) {
Pagination pagination = new Pagination();
pagination.parse(paginationResponse);
int page = pagination.getLastPage();
List<Star> stars = new ArrayList<>();
for (int i = page; page > 0; i--) {
Call<List<Star>> call = createGithubService().getStargazers(
mLogin, mRepositoryName, String.valueOf(i));
Response<List<Star>> response = call.execute();
if (response.isSuccessful()) {
List<Star> starsForPage = response.body();
if (starsForPage != null) {
stars.addAll(starsForPage);
if (starsForPage.size() > 0 | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Star.java
// @SuppressWarnings("all")
// public class Star {
//
// @SerializedName("user")
// public User mUser;
// @SerializedName("starred_at")
// private String mStarredAt;
//
// public String getStarredAt() {
// return mStarredAt;
// }
//
// private class User {
// @SerializedName("id")
// private long mId;
//
// @SerializedName("login")
// private String mLogin;
//
// @SerializedName("url")
// private String mUrl;
//
// public long getId() {
// return mId;
// }
//
// public String getLogin() {
// return mLogin;
// }
//
// public String getUrl() {
// return mUrl;
// }
// }
// }
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/StargazersService.java
import android.support.annotation.WorkerThread;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Star;
import org.eclipse.egit.github.core.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
return this;
}
public StargazersService setDate(long date) {
mDate = date;
return this;
}
@WorkerThread
public List<Star> getStars() throws IOException {
Call<List<Star>> dummyCall = createGithubService().getStargazers(
mLogin, mRepositoryName, mPage);
Response<List<Star>> paginationResponse = dummyCall.execute();
if (paginationResponse.isSuccessful()) {
Pagination pagination = new Pagination();
pagination.parse(paginationResponse);
int page = pagination.getLastPage();
List<Star> stars = new ArrayList<>();
for (int i = page; page > 0; i--) {
Call<List<Star>> call = createGithubService().getStargazers(
mLogin, mRepositoryName, String.valueOf(i));
Response<List<Star>> response = call.execute();
if (response.isSuccessful()) {
List<Star> starsForPage = response.body();
if (starsForPage != null) {
stars.addAll(starsForPage);
if (starsForPage.size() > 0 | && TimeConverter.iso8601ToMilliseconds( |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/dashboard/DashboardContract.java | // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
| import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.dashboard;
class DashboardContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void signOut();
void showTraffic(long id);
void setEmptyState(boolean active);
}
| // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/dashboard/DashboardContract.java
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.dashboard;
class DashboardContract {
interface View extends BaseView<Presenter> {
void setLoadingIndicator(boolean active);
void setRefreshIndicator(boolean active);
void showRepositories(Cursor data);
void openUrl(@NonNull String htmlUrl);
void signOut();
void showTraffic(long id);
void setEmptyState(boolean active);
}
| interface Presenter extends BasePresenter, SwipeRefreshLayout.OnRefreshListener { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/UserContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/User.java
// @SuppressWarnings("all")
// public class User {
//
// String mLogin;
// String mName;
// String mAvatarUrl;
// String mFollowers;
//
// public String getLogin() {
// return mLogin;
// }
//
// public void setLogin(String login) {
// mLogin = login;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// mAvatarUrl = avatarUrl;
// }
//
// public String getFollowers() {
// return mFollowers;
// }
//
// public void setFollowers(String followers) {
// mFollowers = followers;
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.User; | public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_USERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_USERS;
public static final String TABLE_NAME = "users";
public static final String COLUMN_LOGIN = "login";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AVATAR = "avatar";
public static final String COLUMN_FOLLOWERS = "followers";
public static final String[] USERS_COLUMNS = {
_ID,
COLUMN_LOGIN,
COLUMN_NAME,
COLUMN_AVATAR,
COLUMN_FOLLOWERS
};
public static final int COL_ID = 0;
public static final int COL_LOGIN = 1;
public static final int COL_NAME = 2;
public static final int COL_AVATAR = 3;
public static final int COL_FOLLOWERS = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/User.java
// @SuppressWarnings("all")
// public class User {
//
// String mLogin;
// String mName;
// String mAvatarUrl;
// String mFollowers;
//
// public String getLogin() {
// return mLogin;
// }
//
// public void setLogin(String login) {
// mLogin = login;
// }
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// mName = name;
// }
//
// public String getAvatarUrl() {
// return mAvatarUrl;
// }
//
// public void setAvatarUrl(String avatarUrl) {
// mAvatarUrl = avatarUrl;
// }
//
// public String getFollowers() {
// return mFollowers;
// }
//
// public void setFollowers(String followers) {
// mFollowers = followers;
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/UserContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.data.User;
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_USERS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_USERS;
public static final String TABLE_NAME = "users";
public static final String COLUMN_LOGIN = "login";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AVATAR = "avatar";
public static final String COLUMN_FOLLOWERS = "followers";
public static final String[] USERS_COLUMNS = {
_ID,
COLUMN_LOGIN,
COLUMN_NAME,
COLUMN_AVATAR,
COLUMN_FOLLOWERS
};
public static final int COL_ID = 0;
public static final int COL_LOGIN = 1;
public static final int COL_NAME = 2;
public static final int COL_AVATAR = 3;
public static final int COL_FOLLOWERS = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| public static ContentValues buildContentValues(User user) { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/welcome/WelcomeContract.java | // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
| import android.content.Intent;
import android.net.Uri;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView; | /*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.welcome;
class WelcomeContract {
interface View extends BaseView<Presenter> {
void startOAuthIntent(Uri uri);
void startDashboard();
void setLoadingIndicator(boolean active);
void authorizationFailed();
}
| // Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BasePresenter.java
// public interface BasePresenter {
//
// void start(Bundle savedInstanceState);
// }
//
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/BaseView.java
// public interface BaseView<T> {
//
// void setPresenter(T presenter);
//
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/welcome/WelcomeContract.java
import android.content.Intent;
import android.net.Uri;
import com.dmitrymalkovich.android.githubanalytics.BasePresenter;
import com.dmitrymalkovich.android.githubanalytics.BaseView;
/*
* Copyright 2017. Dmitry Malkovich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dmitrymalkovich.android.githubanalytics.welcome;
class WelcomeContract {
interface View extends BaseView<Presenter> {
void startOAuthIntent(Uri uri);
void startDashboard();
void setLoadingIndicator(boolean active);
void authorizationFailed();
}
| interface Presenter extends BasePresenter { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ViewsContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Views; | public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_VIEWS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIEWS;
public static final String TABLE_NAME = "traffic_views";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_VIEWS_COUNT = "count";
public static final String COLUMN_VIEWS_UNIQUES = "uniques";
public static final String COLUMN_VIEWS_TIMESTAMP = "timestamp";
public static final String[] VIEWS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_VIEWS_COUNT,
COLUMN_VIEWS_UNIQUES,
COLUMN_VIEWS_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_VIEWS_COUNT = 2;
public static final int COL_VIEWS_UNIQUES = 3;
public static final int COL_VIEWS_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ViewsContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_VIEWS).build();
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIEWS;
public static final String TABLE_NAME = "traffic_views";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_VIEWS_COUNT = "count";
public static final String COLUMN_VIEWS_UNIQUES = "uniques";
public static final String COLUMN_VIEWS_TIMESTAMP = "timestamp";
public static final String[] VIEWS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_VIEWS_COUNT,
COLUMN_VIEWS_UNIQUES,
COLUMN_VIEWS_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_VIEWS_COUNT = 2;
public static final int COL_VIEWS_UNIQUES = 3;
public static final int COL_VIEWS_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
| public static ContentValues buildContentValues(long repositoryId, Views.View view) { |
DmitryMalkovich/gito-github-client | app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ViewsContract.java | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
| import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Views; |
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIEWS;
public static final String TABLE_NAME = "traffic_views";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_VIEWS_COUNT = "count";
public static final String COLUMN_VIEWS_UNIQUES = "uniques";
public static final String COLUMN_VIEWS_TIMESTAMP = "timestamp";
public static final String[] VIEWS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_VIEWS_COUNT,
COLUMN_VIEWS_UNIQUES,
COLUMN_VIEWS_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_VIEWS_COUNT = 2;
public static final int COL_VIEWS_UNIQUES = 3;
public static final int COL_VIEWS_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, Views.View view) {
String timestamp = view.getTimestamp(); | // Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/time/TimeConverter.java
// public class TimeConverter {
// private static final String LOG_TAG = TimeConverter.class.getSimpleName();
//
// public static long iso8601ToMilliseconds(String date) {
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
// long timeInMilliseconds = 0;
// try {
// Date parsedDate = df.parse(date);
// timeInMilliseconds = parsedDate.getTime();
// } catch (ParseException e) {
// Log.e(LOG_TAG, e.getMessage(), e);
// }
// return timeInMilliseconds;
// }
//
// public static TimeZone getGitHubDefaultTimeZone() {
// return TimeZone.getTimeZone("GMT");
// }
// }
//
// Path: github-api/src/main/java/com/dmitrymalkovich/android/githubapi/core/data/Views.java
// @SuppressWarnings("all")
// public class Views {
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// @SerializedName("views")
// private List<View> mViews;
//
// public List<View> getViews() {
// return mViews;
// }
//
// public static class View {
// @SerializedName("timestamp")
// private String mTimestamp;
//
// @SerializedName("count")
// private String mCount;
//
// @SerializedName("uniques")
// private String mUniques;
//
// public String getTimestamp() {
// return mTimestamp;
// }
//
// public String getCount() {
// return mCount;
// }
//
// public String getUniques() {
// return mUniques;
// }
// }
// }
// Path: app/src/main/java/com/dmitrymalkovich/android/githubanalytics/data/source/local/contract/ViewsContract.java
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
import com.dmitrymalkovich.android.githubapi.core.time.TimeConverter;
import com.dmitrymalkovich.android.githubapi.core.data.Views;
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIEWS;
public static final String TABLE_NAME = "traffic_views";
public static final String COLUMN_REPOSITORY_KEY = "repository_id";
public static final String COLUMN_VIEWS_COUNT = "count";
public static final String COLUMN_VIEWS_UNIQUES = "uniques";
public static final String COLUMN_VIEWS_TIMESTAMP = "timestamp";
public static final String[] VIEWS_COLUMNS = {
_ID,
COLUMN_REPOSITORY_KEY,
COLUMN_VIEWS_COUNT,
COLUMN_VIEWS_UNIQUES,
COLUMN_VIEWS_TIMESTAMP
};
public static final int COL_ID = 0;
public static final int COL_REPOSITORY_KEY = 1;
public static final int COL_VIEWS_COUNT = 2;
public static final int COL_VIEWS_UNIQUES = 3;
public static final int COL_VIEWS_TIMESTAMP = 4;
public static Uri buildUri(long id) {
return ContentUris.withAppendedId(CONTENT_URI, id);
}
public static ContentValues buildContentValues(long repositoryId, Views.View view) {
String timestamp = view.getTimestamp(); | long timeInMilliseconds = TimeConverter.iso8601ToMilliseconds(timestamp); |
perwendel/spark-template-engines | spark-template-water/src/test/java/spark/template/water/WaterTemplateEngineTest.java | // Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static Render render(final Template template, final Request request) {
// return new Render(template, request.raw().getLocale());
// }
//
// Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static WaterTemplateEngine waterEngine() {
// return waterTemplateEngine;
// }
| import static spark.Spark.get;
import static spark.template.water.WaterTemplateEngine.render;
import static spark.template.water.WaterTemplateEngine.waterEngine; | package spark.template.water;
public class WaterTemplateEngineTest {
public static void main(String[] args) { | // Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static Render render(final Template template, final Request request) {
// return new Render(template, request.raw().getLocale());
// }
//
// Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static WaterTemplateEngine waterEngine() {
// return waterTemplateEngine;
// }
// Path: spark-template-water/src/test/java/spark/template/water/WaterTemplateEngineTest.java
import static spark.Spark.get;
import static spark.template.water.WaterTemplateEngine.render;
import static spark.template.water.WaterTemplateEngine.waterEngine;
package spark.template.water;
public class WaterTemplateEngineTest {
public static void main(String[] args) { | get("/home", (req, res) -> render(new HelloPage(), req), waterEngine()); |
perwendel/spark-template-engines | spark-template-water/src/test/java/spark/template/water/WaterTemplateEngineTest.java | // Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static Render render(final Template template, final Request request) {
// return new Render(template, request.raw().getLocale());
// }
//
// Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static WaterTemplateEngine waterEngine() {
// return waterTemplateEngine;
// }
| import static spark.Spark.get;
import static spark.template.water.WaterTemplateEngine.render;
import static spark.template.water.WaterTemplateEngine.waterEngine; | package spark.template.water;
public class WaterTemplateEngineTest {
public static void main(String[] args) { | // Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static Render render(final Template template, final Request request) {
// return new Render(template, request.raw().getLocale());
// }
//
// Path: spark-template-water/src/main/java/spark/template/water/WaterTemplateEngine.java
// public static WaterTemplateEngine waterEngine() {
// return waterTemplateEngine;
// }
// Path: spark-template-water/src/test/java/spark/template/water/WaterTemplateEngineTest.java
import static spark.Spark.get;
import static spark.template.water.WaterTemplateEngine.render;
import static spark.template.water.WaterTemplateEngine.waterEngine;
package spark.template.water;
public class WaterTemplateEngineTest {
public static void main(String[] args) { | get("/home", (req, res) -> render(new HelloPage(), req), waterEngine()); |
perwendel/spark-template-engines | spark-template-rocker/src/test/java/spark/template/rocker/example/RockerTransformerExample.java | // Path: spark-template-rocker/src/main/java/spark/template/rocker/RockerTransformer.java
// public class RockerTransformer implements ResponseTransformer {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String render(final Object o) throws Exception {
// return ((DefaultRockerModel) o).render().toString();
// }
//
// }
| import spark.template.rocker.RockerTransformer;
import static spark.Spark.get; | package spark.template.rocker.example;
public class RockerTransformerExample {
public static void main(String args[]) {
get("/hello", (request, response) -> {
return views.hello.template("Hello Rocker!"); | // Path: spark-template-rocker/src/main/java/spark/template/rocker/RockerTransformer.java
// public class RockerTransformer implements ResponseTransformer {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String render(final Object o) throws Exception {
// return ((DefaultRockerModel) o).render().toString();
// }
//
// }
// Path: spark-template-rocker/src/test/java/spark/template/rocker/example/RockerTransformerExample.java
import spark.template.rocker.RockerTransformer;
import static spark.Spark.get;
package spark.template.rocker.example;
public class RockerTransformerExample {
public static void main(String args[]) {
get("/hello", (request, response) -> {
return views.hello.template("Hello Rocker!"); | }, new RockerTransformer()); |
perwendel/spark-template-engines | spark-template-rocker/src/test/java/spark/template/rocker/example/RockerEngineExample.java | // Path: spark-template-rocker/src/main/java/spark/template/rocker/RockerEngine.java
// public class RockerEngine extends TemplateEngine {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String render(ModelAndView modelAndView) {
// return Rocker.template(modelAndView.getViewName())
// .bind((Map<String,Object>)modelAndView.getModel())
// .render()
// .toString();
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import spark.ModelAndView;
import spark.template.rocker.RockerEngine;
import static spark.Spark.get; | package spark.template.rocker.example;
public class RockerEngineExample {
public static void main(String args[]) {
get("/hello", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("message", "Hello Rocker!");
return new ModelAndView(model, "views/hello.rocker.html"); | // Path: spark-template-rocker/src/main/java/spark/template/rocker/RockerEngine.java
// public class RockerEngine extends TemplateEngine {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String render(ModelAndView modelAndView) {
// return Rocker.template(modelAndView.getViewName())
// .bind((Map<String,Object>)modelAndView.getModel())
// .render()
// .toString();
// }
//
// }
// Path: spark-template-rocker/src/test/java/spark/template/rocker/example/RockerEngineExample.java
import java.util.HashMap;
import java.util.Map;
import spark.ModelAndView;
import spark.template.rocker.RockerEngine;
import static spark.Spark.get;
package spark.template.rocker.example;
public class RockerEngineExample {
public static void main(String args[]) {
get("/hello", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("message", "Hello Rocker!");
return new ModelAndView(model, "views/hello.rocker.html"); | }, new RockerEngine()); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions; | }
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
}
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | public <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions; | }
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
}
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | public <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions; | }
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/SimpleMessageBus.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
}
@Override
public <T extends Event> void publish(T event) {
publish(event, null);
}
/**
* Publish an event asynchronously. Although the publish is
* asynchronous it is still subject to the 60 second request time
* limit. This is why the event handlers themselves are using
* deferred tasks because they are not subject to the request time limit.
*
* By executing this method asynchronously it allows the caller to continue
* without waiting for the individual event handlers to be added
* to the queue for processing.
*
*/
@Override
public <T extends Event> void publish(T event, String queue) {
ThreadExecutor executor = new ThreadExecutor();
executor.execute(new PublishTask(event,queue));
}
/**
* Execute a command synchronously
*
*/
@Override | public <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/domain/Attendee.java | // Path: src/main/java/com/cqrs/appengine/core/StringHelper.java
// public class StringHelper {
//
// public static boolean IsNullOrWhitespace(String text)
// {
// return text == null || text.isEmpty() || text.trim().length() == 0;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
// public abstract class AggregateRootBase implements AggregateRoot {
//
// /**
// * Aggregate id
// */
// protected UUID id = null;
//
// /**
// * list of changes that have occurred since last loaded
// */
// private List<Event> changes = new ArrayList<Event>();
//
// /**
// * returns the expected version
// */
// private int expectedVersion = 0;
//
// @Override
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// @Override
// public void markChangesAsCommitted(){
// changes.clear();
// }
//
// @Override
// public UUID getId(){
// return id;
// }
//
// @Override
// public Iterable<Event> getUncommittedChanges(){
// return changes == null || changes.isEmpty() ? null : changes;
// }
//
// @Override
// public void loadFromHistory(Iterable<Event> history) throws HydrationException {
//
// if(history != null){
// for(Event event : history){
// applyChange(event, false);
// expectedVersion++;
// }
// }
// }
//
// /**
// * Apply the event assuming it is new
// *
// * @param event
// * @throws HydrationException
// */
// protected void applyChange(Event event) throws HydrationException {
// applyChange(event,true);
// }
//
// /**
// * Apply the change by invoking the inherited members apply method that fits the signature of the event passed
// *
// * @param event
// * @param isNew
// * @throws HydrationException
// */
// private void applyChange(Event event, boolean isNew) throws HydrationException {
//
// Method method = null;
//
// try {
// method = this.getClass().getDeclaredMethod("apply", event.getClass());
// } catch (NoSuchMethodException e) {
// //do nothing. This just means that the method signature wasn't found and
// //the aggregate doesn't need to apply any state changes since it wasn't
// //implemented.
// }
//
// if(method != null){
// method.setAccessible(true);
// try {
// method.invoke(this,event);
// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// throw new HydrationException(this.getId(), e.getMessage());
// }
// }
//
// if(isNew){
// changes.add(event);
// }
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.util.UUID;
import com.cqrs.appengine.core.StringHelper;
import com.cqrs.appengine.core.domain.AggregateRootBase;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.sample.domain;
/**
* Class that represents an attendee at a conference
*/
public class Attendee extends AggregateRootBase {
/**
* Flag that determines if the attendee is enabled
*/
private boolean isEnabled = true;
/**
* Id used to confirm an email change request
*/
private UUID confirmationId = null;
/**
* Email address the user has requested a change to
*/
private String unconfirmedEmail = null;
/**
* Default constructor.
*/
public Attendee() {
}
/**
* Constructor used when creating a new attendee
*
* @param attendeeId
* @param email
* @param firstName
* @param lastName
* @throws HydrationException
*/ | // Path: src/main/java/com/cqrs/appengine/core/StringHelper.java
// public class StringHelper {
//
// public static boolean IsNullOrWhitespace(String text)
// {
// return text == null || text.isEmpty() || text.trim().length() == 0;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
// public abstract class AggregateRootBase implements AggregateRoot {
//
// /**
// * Aggregate id
// */
// protected UUID id = null;
//
// /**
// * list of changes that have occurred since last loaded
// */
// private List<Event> changes = new ArrayList<Event>();
//
// /**
// * returns the expected version
// */
// private int expectedVersion = 0;
//
// @Override
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// @Override
// public void markChangesAsCommitted(){
// changes.clear();
// }
//
// @Override
// public UUID getId(){
// return id;
// }
//
// @Override
// public Iterable<Event> getUncommittedChanges(){
// return changes == null || changes.isEmpty() ? null : changes;
// }
//
// @Override
// public void loadFromHistory(Iterable<Event> history) throws HydrationException {
//
// if(history != null){
// for(Event event : history){
// applyChange(event, false);
// expectedVersion++;
// }
// }
// }
//
// /**
// * Apply the event assuming it is new
// *
// * @param event
// * @throws HydrationException
// */
// protected void applyChange(Event event) throws HydrationException {
// applyChange(event,true);
// }
//
// /**
// * Apply the change by invoking the inherited members apply method that fits the signature of the event passed
// *
// * @param event
// * @param isNew
// * @throws HydrationException
// */
// private void applyChange(Event event, boolean isNew) throws HydrationException {
//
// Method method = null;
//
// try {
// method = this.getClass().getDeclaredMethod("apply", event.getClass());
// } catch (NoSuchMethodException e) {
// //do nothing. This just means that the method signature wasn't found and
// //the aggregate doesn't need to apply any state changes since it wasn't
// //implemented.
// }
//
// if(method != null){
// method.setAccessible(true);
// try {
// method.invoke(this,event);
// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// throw new HydrationException(this.getId(), e.getMessage());
// }
// }
//
// if(isNew){
// changes.add(event);
// }
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/domain/Attendee.java
import java.util.UUID;
import com.cqrs.appengine.core.StringHelper;
import com.cqrs.appengine.core.domain.AggregateRootBase;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.sample.domain;
/**
* Class that represents an attendee at a conference
*/
public class Attendee extends AggregateRootBase {
/**
* Flag that determines if the attendee is enabled
*/
private boolean isEnabled = true;
/**
* Id used to confirm an email change request
*/
private UUID confirmationId = null;
/**
* Email address the user has requested a change to
*/
private String unconfirmedEmail = null;
/**
* Default constructor.
*/
public Attendee() {
}
/**
* Constructor used when creating a new attendee
*
* @param attendeeId
* @param email
* @param firstName
* @param lastName
* @throws HydrationException
*/ | private Attendee(UUID attendeeId, String email, String firstName, String lastName) throws HydrationException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/domain/Attendee.java | // Path: src/main/java/com/cqrs/appengine/core/StringHelper.java
// public class StringHelper {
//
// public static boolean IsNullOrWhitespace(String text)
// {
// return text == null || text.isEmpty() || text.trim().length() == 0;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
// public abstract class AggregateRootBase implements AggregateRoot {
//
// /**
// * Aggregate id
// */
// protected UUID id = null;
//
// /**
// * list of changes that have occurred since last loaded
// */
// private List<Event> changes = new ArrayList<Event>();
//
// /**
// * returns the expected version
// */
// private int expectedVersion = 0;
//
// @Override
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// @Override
// public void markChangesAsCommitted(){
// changes.clear();
// }
//
// @Override
// public UUID getId(){
// return id;
// }
//
// @Override
// public Iterable<Event> getUncommittedChanges(){
// return changes == null || changes.isEmpty() ? null : changes;
// }
//
// @Override
// public void loadFromHistory(Iterable<Event> history) throws HydrationException {
//
// if(history != null){
// for(Event event : history){
// applyChange(event, false);
// expectedVersion++;
// }
// }
// }
//
// /**
// * Apply the event assuming it is new
// *
// * @param event
// * @throws HydrationException
// */
// protected void applyChange(Event event) throws HydrationException {
// applyChange(event,true);
// }
//
// /**
// * Apply the change by invoking the inherited members apply method that fits the signature of the event passed
// *
// * @param event
// * @param isNew
// * @throws HydrationException
// */
// private void applyChange(Event event, boolean isNew) throws HydrationException {
//
// Method method = null;
//
// try {
// method = this.getClass().getDeclaredMethod("apply", event.getClass());
// } catch (NoSuchMethodException e) {
// //do nothing. This just means that the method signature wasn't found and
// //the aggregate doesn't need to apply any state changes since it wasn't
// //implemented.
// }
//
// if(method != null){
// method.setAccessible(true);
// try {
// method.invoke(this,event);
// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// throw new HydrationException(this.getId(), e.getMessage());
// }
// }
//
// if(isNew){
// changes.add(event);
// }
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.util.UUID;
import com.cqrs.appengine.core.StringHelper;
import com.cqrs.appengine.core.domain.AggregateRootBase;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.sample.domain;
/**
* Class that represents an attendee at a conference
*/
public class Attendee extends AggregateRootBase {
/**
* Flag that determines if the attendee is enabled
*/
private boolean isEnabled = true;
/**
* Id used to confirm an email change request
*/
private UUID confirmationId = null;
/**
* Email address the user has requested a change to
*/
private String unconfirmedEmail = null;
/**
* Default constructor.
*/
public Attendee() {
}
/**
* Constructor used when creating a new attendee
*
* @param attendeeId
* @param email
* @param firstName
* @param lastName
* @throws HydrationException
*/
private Attendee(UUID attendeeId, String email, String firstName, String lastName) throws HydrationException {
applyChange(new AttendeeRegistered(attendeeId, email, firstName, lastName));
}
/**
* Change the attendee's name
*
* @param firstName
* @param lastName
* @throws IllegalArgumentException
* @throws HydrationException
*/
public void changeName(String firstName, String lastName) throws HydrationException {
/*
* Don't bother checking for parameter validity if the attendee isn't enabled
*/
if(!isEnabled) throw new IllegalStateException("Operation not allowed. The attendee is disabled");
/*
* Only change state if the data is valid
*/ | // Path: src/main/java/com/cqrs/appengine/core/StringHelper.java
// public class StringHelper {
//
// public static boolean IsNullOrWhitespace(String text)
// {
// return text == null || text.isEmpty() || text.trim().length() == 0;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
// public abstract class AggregateRootBase implements AggregateRoot {
//
// /**
// * Aggregate id
// */
// protected UUID id = null;
//
// /**
// * list of changes that have occurred since last loaded
// */
// private List<Event> changes = new ArrayList<Event>();
//
// /**
// * returns the expected version
// */
// private int expectedVersion = 0;
//
// @Override
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// @Override
// public void markChangesAsCommitted(){
// changes.clear();
// }
//
// @Override
// public UUID getId(){
// return id;
// }
//
// @Override
// public Iterable<Event> getUncommittedChanges(){
// return changes == null || changes.isEmpty() ? null : changes;
// }
//
// @Override
// public void loadFromHistory(Iterable<Event> history) throws HydrationException {
//
// if(history != null){
// for(Event event : history){
// applyChange(event, false);
// expectedVersion++;
// }
// }
// }
//
// /**
// * Apply the event assuming it is new
// *
// * @param event
// * @throws HydrationException
// */
// protected void applyChange(Event event) throws HydrationException {
// applyChange(event,true);
// }
//
// /**
// * Apply the change by invoking the inherited members apply method that fits the signature of the event passed
// *
// * @param event
// * @param isNew
// * @throws HydrationException
// */
// private void applyChange(Event event, boolean isNew) throws HydrationException {
//
// Method method = null;
//
// try {
// method = this.getClass().getDeclaredMethod("apply", event.getClass());
// } catch (NoSuchMethodException e) {
// //do nothing. This just means that the method signature wasn't found and
// //the aggregate doesn't need to apply any state changes since it wasn't
// //implemented.
// }
//
// if(method != null){
// method.setAccessible(true);
// try {
// method.invoke(this,event);
// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// throw new HydrationException(this.getId(), e.getMessage());
// }
// }
//
// if(isNew){
// changes.add(event);
// }
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/domain/Attendee.java
import java.util.UUID;
import com.cqrs.appengine.core.StringHelper;
import com.cqrs.appengine.core.domain.AggregateRootBase;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.sample.domain;
/**
* Class that represents an attendee at a conference
*/
public class Attendee extends AggregateRootBase {
/**
* Flag that determines if the attendee is enabled
*/
private boolean isEnabled = true;
/**
* Id used to confirm an email change request
*/
private UUID confirmationId = null;
/**
* Email address the user has requested a change to
*/
private String unconfirmedEmail = null;
/**
* Default constructor.
*/
public Attendee() {
}
/**
* Constructor used when creating a new attendee
*
* @param attendeeId
* @param email
* @param firstName
* @param lastName
* @throws HydrationException
*/
private Attendee(UUID attendeeId, String email, String firstName, String lastName) throws HydrationException {
applyChange(new AttendeeRegistered(attendeeId, email, firstName, lastName));
}
/**
* Change the attendee's name
*
* @param firstName
* @param lastName
* @throws IllegalArgumentException
* @throws HydrationException
*/
public void changeName(String firstName, String lastName) throws HydrationException {
/*
* Don't bother checking for parameter validity if the attendee isn't enabled
*/
if(!isEnabled) throw new IllegalStateException("Operation not allowed. The attendee is disabled");
/*
* Only change state if the data is valid
*/ | if(!StringHelper.IsNullOrWhitespace(firstName) && !StringHelper.IsNullOrWhitespace(lastName)) { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeNameChangedEventHandler.java | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeNameChanged.java
// public class AttendeeNameChanged implements Event, Serializable{
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private String firstName;
// private String lastName;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeNameChanged(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param firstName
// * @param lastName
// */
// public AttendeeNameChanged(UUID attendeeId, String firstName, String lastName){
// this.attendeeId = attendeeId;
// this.firstName = firstName;
// this.lastName = lastName;
// }
//
// /**
// * Get the first name
// * @return
// */
// public String getFirstName(){
// return firstName;
// }
//
// /**
// * Get the last name
// * @return
// */
// public String getLastName(){
// return lastName;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
| import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeNameChanged;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction; | package com.cqrs.appengine.sample.handlers.events;
/**
* Deferred task for handling an attendee name change
*/
public class AttendeeNameChangedEventHandler extends EventHandler<AttendeeNameChanged>{
private static final long serialVersionUID = 1L;
public AttendeeNameChangedEventHandler(AttendeeNameChanged event){
super(event);
}
@Override
public void run() {
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction transaction = datastoreService.beginTransaction();
Key attendeeKey = KeyFactory.createKey("Attendee", event.getAttendeeId().toString());
Entity attendee = null;
try {
attendee = datastoreService.get(attendeeKey);
attendee.setProperty("FirstName", event.getFirstName());
attendee.setProperty("LastName", event.getLastName());
datastoreService.put(attendee);
transaction.commit();
} catch (EntityNotFoundException e) { | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeNameChanged.java
// public class AttendeeNameChanged implements Event, Serializable{
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private String firstName;
// private String lastName;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeNameChanged(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param firstName
// * @param lastName
// */
// public AttendeeNameChanged(UUID attendeeId, String firstName, String lastName){
// this.attendeeId = attendeeId;
// this.firstName = firstName;
// this.lastName = lastName;
// }
//
// /**
// * Get the first name
// * @return
// */
// public String getFirstName(){
// return firstName;
// }
//
// /**
// * Get the last name
// * @return
// */
// public String getLastName(){
// return lastName;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeNameChangedEventHandler.java
import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeNameChanged;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
package com.cqrs.appengine.sample.handlers.events;
/**
* Deferred task for handling an attendee name change
*/
public class AttendeeNameChangedEventHandler extends EventHandler<AttendeeNameChanged>{
private static final long serialVersionUID = 1L;
public AttendeeNameChangedEventHandler(AttendeeNameChanged event){
super(event);
}
@Override
public void run() {
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction transaction = datastoreService.beginTransaction();
Key attendeeKey = KeyFactory.createKey("Attendee", event.getAttendeeId().toString());
Entity attendee = null;
try {
attendee = datastoreService.get(attendeeKey);
attendee.setProperty("FirstName", event.getFirstName());
attendee.setProperty("LastName", event.getLastName());
datastoreService.put(attendee);
transaction.commit();
} catch (EntityNotFoundException e) { | MessageLog.log(e); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeDisabledEventHandler.java | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeDisabled.java
// public class AttendeeDisabled implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private DisableReason reason;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeDisabled(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param reason
// */
// public AttendeeDisabled(UUID attendeeId, DisableReason reason){
// this.attendeeId = attendeeId;
// this.reason = reason;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
//
// /**
// * Get the reason
// *
// * @return
// */
// public DisableReason getReason(){
// return reason;
// }
// }
| import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeDisabled; | package com.cqrs.appengine.sample.handlers.events;
public class AttendeeDisabledEventHandler extends EventHandler<AttendeeDisabled> {
private static final long serialVersionUID = 1L;
public AttendeeDisabledEventHandler(AttendeeDisabled event) {
super(event);
}
@Override
public void run() {
| // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeDisabled.java
// public class AttendeeDisabled implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private DisableReason reason;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeDisabled(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param reason
// */
// public AttendeeDisabled(UUID attendeeId, DisableReason reason){
// this.attendeeId = attendeeId;
// this.reason = reason;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
//
// /**
// * Get the reason
// *
// * @return
// */
// public DisableReason getReason(){
// return reason;
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeDisabledEventHandler.java
import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeDisabled;
package com.cqrs.appengine.sample.handlers.events;
public class AttendeeDisabledEventHandler extends EventHandler<AttendeeDisabled> {
private static final long serialVersionUID = 1L;
public AttendeeDisabledEventHandler(AttendeeDisabled event) {
super(event);
}
@Override
public void run() {
| MessageLog.log(String.format("Attendee %s Disabled.", event.getAttendeeId().toString())); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeChangeEmailConfirmedEventHandler.java | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeChangeEmailConfirmed.java
// public class AttendeeChangeEmailConfirmed implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private UUID confirmationId;
// private String email;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeChangeEmailConfirmed(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param confirmationId
// * @param email
// */
// public AttendeeChangeEmailConfirmed(UUID attendeeId, UUID confirmationId, String email){
// this.attendeeId = attendeeId;
// this.confirmationId = confirmationId;
// this.email = email;
// }
//
// /**
// * Get the email
// * @return
// */
// public String getEmail(){
// return email;
// }
//
// /**
// * Get the confirmation id to verify the email change
// *
// * @return
// */
// public UUID getConfirmationId(){
// return confirmationId;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
| import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeChangeEmailConfirmed;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction; | package com.cqrs.appengine.sample.handlers.events;
public class AttendeeChangeEmailConfirmedEventHandler extends EventHandler<AttendeeChangeEmailConfirmed> {
private static final long serialVersionUID = 1L;
public AttendeeChangeEmailConfirmedEventHandler(AttendeeChangeEmailConfirmed event) {
super(event);
}
@Override
public void run() {
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction transaction = datastoreService.beginTransaction();
Key attendeeKey = KeyFactory.createKey("Attendee", event.getAttendeeId().toString());
Entity attendee = null;
try {
attendee = datastoreService.get(attendeeKey);
attendee.setProperty("Email", event.getEmail());
datastoreService.put(attendee);
transaction.commit();
} catch (EntityNotFoundException e) { | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeChangeEmailConfirmed.java
// public class AttendeeChangeEmailConfirmed implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private UUID confirmationId;
// private String email;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeChangeEmailConfirmed(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param confirmationId
// * @param email
// */
// public AttendeeChangeEmailConfirmed(UUID attendeeId, UUID confirmationId, String email){
// this.attendeeId = attendeeId;
// this.confirmationId = confirmationId;
// this.email = email;
// }
//
// /**
// * Get the email
// * @return
// */
// public String getEmail(){
// return email;
// }
//
// /**
// * Get the confirmation id to verify the email change
// *
// * @return
// */
// public UUID getConfirmationId(){
// return confirmationId;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeChangeEmailConfirmedEventHandler.java
import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeChangeEmailConfirmed;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
package com.cqrs.appengine.sample.handlers.events;
public class AttendeeChangeEmailConfirmedEventHandler extends EventHandler<AttendeeChangeEmailConfirmed> {
private static final long serialVersionUID = 1L;
public AttendeeChangeEmailConfirmedEventHandler(AttendeeChangeEmailConfirmed event) {
super(event);
}
@Override
public void run() {
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
Transaction transaction = datastoreService.beginTransaction();
Key attendeeKey = KeyFactory.createKey("Attendee", event.getAttendeeId().toString());
Entity attendee = null;
try {
attendee = datastoreService.get(attendeeKey);
attendee.setProperty("Email", event.getEmail());
datastoreService.put(attendee);
transaction.commit();
} catch (EntityNotFoundException e) { | MessageLog.log(e); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.domain;
/**
* Simple interface to an aggregate root
*/
public interface AggregateRoot {
/**
* get the Id
*
* @return
*/
UUID getId();
/**
* Gets all change events since the
* original hydration. If there are no
* changes then null is returned
*
* @return
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.domain;
/**
* Simple interface to an aggregate root
*/
public interface AggregateRoot {
/**
* get the Id
*
* @return
*/
UUID getId();
/**
* Gets all change events since the
* original hydration. If there are no
* changes then null is returned
*
* @return
*/ | Iterable<Event> getUncommittedChanges(); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.domain;
/**
* Simple interface to an aggregate root
*/
public interface AggregateRoot {
/**
* get the Id
*
* @return
*/
UUID getId();
/**
* Gets all change events since the
* original hydration. If there are no
* changes then null is returned
*
* @return
*/
Iterable<Event> getUncommittedChanges();
/**
* Mark all changes a committed
*/
void markChangesAsCommitted();
/**
* load the aggregate root
*
* @param history
* @throws HydrationException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.domain;
/**
* Simple interface to an aggregate root
*/
public interface AggregateRoot {
/**
* get the Id
*
* @return
*/
UUID getId();
/**
* Gets all change events since the
* original hydration. If there are no
* changes then null is returned
*
* @return
*/
Iterable<Event> getUncommittedChanges();
/**
* Mark all changes a committed
*/
void markChangesAsCommitted();
/**
* load the aggregate root
*
* @param history
* @throws HydrationException
*/ | void loadFromHistory(Iterable<Event> history) throws HydrationException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeEmailChangedEventHandler.java | // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeEmailChanged.java
// public class AttendeeEmailChanged implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private UUID confirmationId;
// private String email;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeEmailChanged(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param firstName
// * @param lastName
// */
// public AttendeeEmailChanged(UUID attendeeId, String email){
// this.attendeeId = attendeeId;
// this.email = email;
// this.confirmationId = UUID.randomUUID();
// }
//
// /**
// * Get the email
// * @return
// */
// public String getEmail(){
// return email;
// }
//
// /**
// * Get the confirmation id to verify the email change
// *
// * @return
// */
// public UUID getConfirmationId(){
// return confirmationId;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
| import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeEmailChanged; | package com.cqrs.appengine.sample.handlers.events;
public class AttendeeEmailChangedEventHandler extends EventHandler<AttendeeEmailChanged>{
private static final long serialVersionUID = 1L;
public AttendeeEmailChangedEventHandler(AttendeeEmailChanged event) {
super(event);
// TODO Auto-generated constructor stub
}
@Override
public void run() {
| // Path: src/main/java/com/cqrs/appengine/core/messaging/EventHandler.java
// @SuppressWarnings("serial")
// public abstract class EventHandler<T extends Event> implements DeferredTask {
//
// /**
// * The event
// */
// protected T event;
//
// /**
// * Default constructor
// *
// * @param event
// */
// public EventHandler(T event){
// this.event = event;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/MessageLog.java
// public class MessageLog {
//
// private static final String LOG_NAME = "Simple CQRS Service Log";
//
// private static final Logger log = Logger.getLogger(LOG_NAME);
//
// static {
// log.setLevel(java.util.logging.Level.FINEST);
// }
//
// /**
// * Log an informational message
// *
// * @param message
// */
// public static void log(String message){
// log.log(Level.INFO, message);
// }
//
// /**
// * Log an exception
// *
// * @param e
// */
// public static void log(Exception e){
//
// if(e == null)
// return;
//
// log.log(Level.SEVERE, e.getClass().getName(), e);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/sample/domain/AttendeeEmailChanged.java
// public class AttendeeEmailChanged implements Event, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private UUID attendeeId;
// private UUID confirmationId;
// private String email;
//
// /**
// * Default constructor for serialization
// */
// public AttendeeEmailChanged(){}
//
// /**
// * Constructor
// *
// * @param attendeeId
// * @param firstName
// * @param lastName
// */
// public AttendeeEmailChanged(UUID attendeeId, String email){
// this.attendeeId = attendeeId;
// this.email = email;
// this.confirmationId = UUID.randomUUID();
// }
//
// /**
// * Get the email
// * @return
// */
// public String getEmail(){
// return email;
// }
//
// /**
// * Get the confirmation id to verify the email change
// *
// * @return
// */
// public UUID getConfirmationId(){
// return confirmationId;
// }
//
// /**
// * Get the attendee Id
// * @return
// */
// public UUID getAttendeeId(){
// return attendeeId;
// }
// }
// Path: src/main/java/com/cqrs/appengine/sample/handlers/events/AttendeeEmailChangedEventHandler.java
import com.cqrs.appengine.core.messaging.EventHandler;
import com.cqrs.appengine.sample.MessageLog;
import com.cqrs.appengine.sample.domain.AttendeeEmailChanged;
package com.cqrs.appengine.sample.handlers.events;
public class AttendeeEmailChangedEventHandler extends EventHandler<AttendeeEmailChanged>{
private static final long serialVersionUID = 1L;
public AttendeeEmailChangedEventHandler(AttendeeEmailChanged event) {
super(event);
// TODO Auto-generated constructor stub
}
@Override
public void run() {
| MessageLog.log(String.format("Attendee Id %s requested to change email address to : %s.", event.getAttendeeId().toString(), event.getEmail())); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/messaging/MessageBus.java
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.core.messaging;
/**
* Interface for a simple message bus
*/
public interface MessageBus{
/**
* Register a command handler
*
* @param aClass
* @param handler
*/
<T extends Command> void registerCommandHandler(Class<T> aClass, CommandHandler<T> handler);
/**
* Register an event handler
*
* @param aClass
* @param handler
*/
<T extends Event, H extends EventHandler<T>> void registerEventHandler(Class<T> aClass, Class<H> handler);
/**
* Publish an event to the default queue
*
* @param event
*/
<T extends Event> void publish(T event);
/**
* Publish an event to the specified queue
*
* @param event
* @param queue
*/
<T extends Event> void publish(T event, String queue);
/**
* Execute a command
*
* @param command
* @throws EventCollisionException
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | <T extends Command> void send(T command) throws EventCollisionException, HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventStore.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Interface to support basic event store functionality
*/
interface EventStore {
/**
* Persist the changes
*
* @param aggregateId
* @param expectedVersion
* @param events
* @throws EventCollisionException
*/
void saveEvents(UUID aggregateId, int expectedVersion, Iterable<Event> events) throws EventCollisionException;
/**
* Retrieves the events
*
* @param aggregateId
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventStore.java
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Interface to support basic event store functionality
*/
interface EventStore {
/**
* Persist the changes
*
* @param aggregateId
* @param expectedVersion
* @param events
* @throws EventCollisionException
*/
void saveEvents(UUID aggregateId, int expectedVersion, Iterable<Event> events) throws EventCollisionException;
/**
* Retrieves the events
*
* @param aggregateId
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | Iterable<Event> getEvents(UUID aggregateId) throws HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventStore.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Interface to support basic event store functionality
*/
interface EventStore {
/**
* Persist the changes
*
* @param aggregateId
* @param expectedVersion
* @param events
* @throws EventCollisionException
*/
void saveEvents(UUID aggregateId, int expectedVersion, Iterable<Event> events) throws EventCollisionException;
/**
* Retrieves the events
*
* @param aggregateId
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventStore.java
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Interface to support basic event store functionality
*/
interface EventStore {
/**
* Persist the changes
*
* @param aggregateId
* @param expectedVersion
* @param events
* @throws EventCollisionException
*/
void saveEvents(UUID aggregateId, int expectedVersion, Iterable<Event> events) throws EventCollisionException;
/**
* Retrieves the events
*
* @param aggregateId
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | Iterable<Event> getEvents(UUID aggregateId) throws HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/Repository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.core.persistence;
/**
* Interface for a repository implementation
*
* @param <T>
*/
public interface Repository<T extends AggregateRoot> {
/**
* Persists the aggregate
*
* @param aggregate
* @throws EventCollisionException
*/
void save(T aggregate) throws EventCollisionException;
/**
* Get the aggregate
*
* @param id
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/Repository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.core.persistence;
/**
* Interface for a repository implementation
*
* @param <T>
*/
public interface Repository<T extends AggregateRoot> {
/**
* Persists the aggregate
*
* @param aggregate
* @throws EventCollisionException
*/
void save(T aggregate) throws EventCollisionException;
/**
* Get the aggregate
*
* @param id
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | T getById(UUID id) throws HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/Repository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException; | package com.cqrs.appengine.core.persistence;
/**
* Interface for a repository implementation
*
* @param <T>
*/
public interface Repository<T extends AggregateRoot> {
/**
* Persists the aggregate
*
* @param aggregate
* @throws EventCollisionException
*/
void save(T aggregate) throws EventCollisionException;
/**
* Get the aggregate
*
* @param id
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/Repository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
package com.cqrs.appengine.core.persistence;
/**
* Interface for a repository implementation
*
* @param <T>
*/
public interface Repository<T extends AggregateRoot> {
/**
* Persists the aggregate
*
* @param aggregate
* @throws EventCollisionException
*/
void save(T aggregate) throws EventCollisionException;
/**
* Get the aggregate
*
* @param id
* @return
* @throws HydrationException
* @throws AggregateNotFoundException
*/ | T getById(UUID id) throws HydrationException, AggregateNotFoundException; |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.domain;
/**
* Base class for aggregate root implementations
*/
public abstract class AggregateRootBase implements AggregateRoot {
/**
* Aggregate id
*/
protected UUID id = null;
/**
* list of changes that have occurred since last loaded
*/ | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.domain;
/**
* Base class for aggregate root implementations
*/
public abstract class AggregateRootBase implements AggregateRoot {
/**
* Aggregate id
*/
protected UUID id = null;
/**
* list of changes that have occurred since last loaded
*/ | private List<Event> changes = new ArrayList<Event>(); |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.domain;
/**
* Base class for aggregate root implementations
*/
public abstract class AggregateRootBase implements AggregateRoot {
/**
* Aggregate id
*/
protected UUID id = null;
/**
* list of changes that have occurred since last loaded
*/
private List<Event> changes = new ArrayList<Event>();
/**
* returns the expected version
*/
private int expectedVersion = 0;
@Override
public int getExpectedVersion(){
return expectedVersion;
}
@Override
public void markChangesAsCommitted(){
changes.clear();
}
@Override
public UUID getId(){
return id;
}
@Override
public Iterable<Event> getUncommittedChanges(){
return changes == null || changes.isEmpty() ? null : changes;
}
@Override | // Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRootBase.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.domain;
/**
* Base class for aggregate root implementations
*/
public abstract class AggregateRootBase implements AggregateRoot {
/**
* Aggregate id
*/
protected UUID id = null;
/**
* list of changes that have occurred since last loaded
*/
private List<Event> changes = new ArrayList<Event>();
/**
* returns the expected version
*/
private int expectedVersion = 0;
@Override
public int getExpectedVersion(){
return expectedVersion;
}
@Override
public void markChangesAsCommitted(){
changes.clear();
}
@Override
public UUID getId(){
return id;
}
@Override
public Iterable<Event> getUncommittedChanges(){
return changes == null || changes.isEmpty() ? null : changes;
}
@Override | public void loadFromHistory(Iterable<Event> history) throws HydrationException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override | public void save(T aggregate) throws EventCollisionException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override | public T getById(UUID id) throws HydrationException, AggregateNotFoundException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override | public T getById(UUID id) throws HydrationException, AggregateNotFoundException { |
dannormington/appengine-cqrs | src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
| import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event; | package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override
public T getById(UUID id) throws HydrationException, AggregateNotFoundException {
/*
* get the events from the event store
*/ | // Path: src/main/java/com/cqrs/appengine/core/domain/AggregateRoot.java
// public interface AggregateRoot {
//
// /**
// * get the Id
// *
// * @return
// */
// UUID getId();
//
// /**
// * Gets all change events since the
// * original hydration. If there are no
// * changes then null is returned
// *
// * @return
// */
// Iterable<Event> getUncommittedChanges();
//
// /**
// * Mark all changes a committed
// */
// void markChangesAsCommitted();
//
// /**
// * load the aggregate root
// *
// * @param history
// * @throws HydrationException
// */
// void loadFromHistory(Iterable<Event> history) throws HydrationException;
//
// /**
// * Returns the version of the aggregate when it was hydrated
// * @return
// */
// int getExpectedVersion();
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/AggregateNotFoundException.java
// public class AggregateNotFoundException extends AggregateException {
//
// private static final String ERROR_TEXT = "The aggregate you requested cannot be found.";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Constructor
// *
// * @param aggregateId
// */
// public AggregateNotFoundException(UUID aggregateId) {
// super(aggregateId, ERROR_TEXT);
// }
//
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/EventCollisionException.java
// public class EventCollisionException extends AggregateException {
//
// private static final String ERROR_TEXT = "Data has been changed between loading and state changes.";
//
// private static final long serialVersionUID = 1L;
//
// private int expectedVersion;
// private Date dateOccurred;
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion){
// this(aggregateId, expectedVersion, ERROR_TEXT);
// }
//
// /**
// * Constructor
// *
// * @param aggregateId
// * @param expectedVersion
// * @param message
// */
// public EventCollisionException(UUID aggregateId, int expectedVersion, String message){
// super(aggregateId, message);
// this.expectedVersion = expectedVersion;
// this.dateOccurred = new Date();
// }
//
// /**
// * Get the expected version when the collision occurred
// *
// * @return
// */
// public int getExpectedVersion(){
// return expectedVersion;
// }
//
// /**
// * Get the date the exception occurred
// *
// * @return
// */
// public Date getDateOccurred(){
// return dateOccurred;
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/exceptions/HydrationException.java
// public class HydrationException extends AggregateException {
//
// private static final String ERROR_TEXT = "Loading the data failed";
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Default constructor
// *
// * @param aggregateId
// */
// public HydrationException(UUID aggregateId){
// super(aggregateId, ERROR_TEXT);
// }
//
// /**
// * Constructor to provide specific error reason for the hydration exception
// *
// * @param aggregateId
// * @param error
// */
// public HydrationException(UUID aggregateId, String error){
// super(aggregateId, error);
// }
// }
//
// Path: src/main/java/com/cqrs/appengine/core/messaging/Event.java
// public interface Event {
//
// }
// Path: src/main/java/com/cqrs/appengine/core/persistence/EventRepository.java
import java.util.UUID;
import com.cqrs.appengine.core.domain.AggregateRoot;
import com.cqrs.appengine.core.exceptions.AggregateNotFoundException;
import com.cqrs.appengine.core.exceptions.EventCollisionException;
import com.cqrs.appengine.core.exceptions.HydrationException;
import com.cqrs.appengine.core.messaging.Event;
package com.cqrs.appengine.core.persistence;
/**
* Implementation of a simple event repository
*
* @param <T>
*/
public class EventRepository<T extends AggregateRoot> implements Repository<T> {
/**
* Instance of the event store
*/
private EventStore eventStore;
/**
* The class type that the repository is working with
*/
private Class<T> aClass;
/**
* Default Constructor
*
* @param aClass
*/
public EventRepository(Class<T> aClass){
this.aClass = aClass;
eventStore = new AppEngineEventStore();
}
/**
* Constructor to be used when specifying a specific
* queue for events to be published to
*
* @param aClass
*/
public EventRepository(Class<T> aClass, String queue){
this.aClass = aClass;
eventStore = new AppEngineEventStore(queue);
}
@Override
public void save(T aggregate) throws EventCollisionException {
eventStore.saveEvents(aggregate.getId(), aggregate.getExpectedVersion(), aggregate.getUncommittedChanges());
aggregate.markChangesAsCommitted();
}
@Override
public T getById(UUID id) throws HydrationException, AggregateNotFoundException {
/*
* get the events from the event store
*/ | Iterable<Event> history = eventStore.getEvents(id); |
reoky/android-crackme-challenge | challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/fragments/AboutFragment.java | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/listeners/AboutFragmentOnClickListener.java
// public class AboutFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
// case R.id.button_quit:
// view.setEnabled(false);
// System.exit(0);
// }
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.reoky.crackme.challengenine.R;
import com.reoky.crackme.challengenine.listeners.AboutFragmentOnClickListener; | package com.reoky.crackme.challengenine.fragments;
public class AboutFragment extends Fragment {
public AboutFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the view
View view = inflater.inflate(R.layout.fragment_about, container, false);
// Handle the quit button being pressed
final Button quitButton = (Button) view.findViewById(R.id.button_quit); | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/listeners/AboutFragmentOnClickListener.java
// public class AboutFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
// case R.id.button_quit:
// view.setEnabled(false);
// System.exit(0);
// }
// }
// }
// Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/fragments/AboutFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.reoky.crackme.challengenine.R;
import com.reoky.crackme.challengenine.listeners.AboutFragmentOnClickListener;
package com.reoky.crackme.challengenine.fragments;
public class AboutFragment extends Fragment {
public AboutFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the view
View view = inflater.inflate(R.layout.fragment_about, container, false);
// Handle the quit button being pressed
final Button quitButton = (Button) view.findViewById(R.id.button_quit); | quitButton.setOnClickListener(new AboutFragmentOnClickListener()); |
reoky/android-crackme-challenge | challenge-six/app/src/main/java/com/reoky/crackme/challengesix/fragments/ChallengeSixFragment.java | // Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/listeners/ChallengeSixFragmentOnClickListener.java
// public class ChallengeSixFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// View parent = (View) view.getParent().getParent(); // TextGuess is in the parent parent view
// switch (view.getId()) {
// case R.id.challenge_one_button_check:
//
// if (parent != null) {
// EditText textGuess = (EditText) parent.findViewById(R.id.challenge_one_text_guess);
//
// // Check to see if the user beat the challenge. The code that was here before was
// // silly. (And actually for a different type of challenge)
// if (textGuess.getText().toString().toLowerCase().equals("poorly-protected-secret")) {
// textGuess.setTextColor(parent.getResources().getColor(R.color.color_nebula));
// Vibrator vibrator = (Vibrator) parent.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibrator.vibrate(400);
// Toast.makeText(parent.getContext(), "You\'ve completed this challenge!", Toast.LENGTH_LONG).show();
// } else {
// textGuess.setTextColor(parent.getResources().getColor(R.color.color_nebula_dark));
// Toast.makeText(parent.getContext(), "Sorry, that\'s not right..", Toast.LENGTH_SHORT).show();
// }
// }
// break;
// case R.id.button_write_file:
// final Button buttonWrite = (Button) parent.findViewById(R.id.button_write_file);
//
// // Check to see if the file already exists
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// file.delete();
// buttonWrite.setText(R.string.string_challenge_write_file);
// Toast.makeText(parent.getContext(), "File Deleted", Toast.LENGTH_LONG).show();
//
// } else {
// try {
// FileOutputStream fileOutputStream = parent.getContext().openFileOutput("ANSWER", Context.MODE_WORLD_READABLE);
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
// outputStreamWriter.write("poorly-protected-secret");
// outputStreamWriter.flush();
// outputStreamWriter.close();
// Toast.makeText(parent.getContext(), "File Written", Toast.LENGTH_LONG).show();
// }
// catch (FileNotFoundException e) { e.printStackTrace(); }
// catch (IOException e) { e.printStackTrace(); }
//
// // Change the text on the button to delete
// buttonWrite.setText(R.string.string_challenge_delete_file);
// }
// break;
// }
// }
// }
| import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.reoky.crackme.challengesix.R;
import com.reoky.crackme.challengesix.listeners.ChallengeSixFragmentOnClickListener;
import java.io.File; | package com.reoky.crackme.challengesix.fragments;
public class ChallengeSixFragment extends Fragment {
public ChallengeSixFragment() {}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
// Handle the user checking their answer
final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check); | // Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/listeners/ChallengeSixFragmentOnClickListener.java
// public class ChallengeSixFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// View parent = (View) view.getParent().getParent(); // TextGuess is in the parent parent view
// switch (view.getId()) {
// case R.id.challenge_one_button_check:
//
// if (parent != null) {
// EditText textGuess = (EditText) parent.findViewById(R.id.challenge_one_text_guess);
//
// // Check to see if the user beat the challenge. The code that was here before was
// // silly. (And actually for a different type of challenge)
// if (textGuess.getText().toString().toLowerCase().equals("poorly-protected-secret")) {
// textGuess.setTextColor(parent.getResources().getColor(R.color.color_nebula));
// Vibrator vibrator = (Vibrator) parent.getContext().getSystemService(Context.VIBRATOR_SERVICE);
// vibrator.vibrate(400);
// Toast.makeText(parent.getContext(), "You\'ve completed this challenge!", Toast.LENGTH_LONG).show();
// } else {
// textGuess.setTextColor(parent.getResources().getColor(R.color.color_nebula_dark));
// Toast.makeText(parent.getContext(), "Sorry, that\'s not right..", Toast.LENGTH_SHORT).show();
// }
// }
// break;
// case R.id.button_write_file:
// final Button buttonWrite = (Button) parent.findViewById(R.id.button_write_file);
//
// // Check to see if the file already exists
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// file.delete();
// buttonWrite.setText(R.string.string_challenge_write_file);
// Toast.makeText(parent.getContext(), "File Deleted", Toast.LENGTH_LONG).show();
//
// } else {
// try {
// FileOutputStream fileOutputStream = parent.getContext().openFileOutput("ANSWER", Context.MODE_WORLD_READABLE);
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
// outputStreamWriter.write("poorly-protected-secret");
// outputStreamWriter.flush();
// outputStreamWriter.close();
// Toast.makeText(parent.getContext(), "File Written", Toast.LENGTH_LONG).show();
// }
// catch (FileNotFoundException e) { e.printStackTrace(); }
// catch (IOException e) { e.printStackTrace(); }
//
// // Change the text on the button to delete
// buttonWrite.setText(R.string.string_challenge_delete_file);
// }
// break;
// }
// }
// }
// Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/fragments/ChallengeSixFragment.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.reoky.crackme.challengesix.R;
import com.reoky.crackme.challengesix.listeners.ChallengeSixFragmentOnClickListener;
import java.io.File;
package com.reoky.crackme.challengesix.fragments;
public class ChallengeSixFragment extends Fragment {
public ChallengeSixFragment() {}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
// Handle the user checking their answer
final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check); | buttonCheck.setOnClickListener(new ChallengeSixFragmentOnClickListener()); |
reoky/android-crackme-challenge | challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/adaptors/ChallengePagerAdapter.java | // Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
//
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/ChallengeTenFragment.java
// public class ChallengeTenFragment extends Fragment {
//
// public ChallengeTenFragment() {}
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
//
// // Handle the user checking their answer
// final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check);
// buttonCheck.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Wire button_write_file to ChallengeTenFragmentOnClickListener()
// final Button buttonWriteFile = (Button) view.findViewById(R.id.button_write_file);
// buttonWriteFile.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Sometimes it takes someone outside the box to see why we really need a box at all
// // think about it...
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// buttonWriteFile.setText(R.string.string_challenge_delete_file);
// } else {
// buttonWriteFile.setText(R.string.string_challenge_write_file);
// }
//
// return view;
// }
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengeten.fragments.AboutFragment;
import com.reoky.crackme.challengeten.fragments.ChallengeTenFragment;
import com.reoky.crackme.challengeten.fragments.HintFragment; | package com.reoky.crackme.challengeten.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: | // Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
//
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/ChallengeTenFragment.java
// public class ChallengeTenFragment extends Fragment {
//
// public ChallengeTenFragment() {}
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
//
// // Handle the user checking their answer
// final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check);
// buttonCheck.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Wire button_write_file to ChallengeTenFragmentOnClickListener()
// final Button buttonWriteFile = (Button) view.findViewById(R.id.button_write_file);
// buttonWriteFile.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Sometimes it takes someone outside the box to see why we really need a box at all
// // think about it...
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// buttonWriteFile.setText(R.string.string_challenge_delete_file);
// } else {
// buttonWriteFile.setText(R.string.string_challenge_write_file);
// }
//
// return view;
// }
// }
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/adaptors/ChallengePagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengeten.fragments.AboutFragment;
import com.reoky.crackme.challengeten.fragments.ChallengeTenFragment;
import com.reoky.crackme.challengeten.fragments.HintFragment;
package com.reoky.crackme.challengeten.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: | return new ChallengeTenFragment(); |
reoky/android-crackme-challenge | challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/adaptors/ChallengePagerAdapter.java | // Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
//
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/ChallengeTenFragment.java
// public class ChallengeTenFragment extends Fragment {
//
// public ChallengeTenFragment() {}
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
//
// // Handle the user checking their answer
// final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check);
// buttonCheck.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Wire button_write_file to ChallengeTenFragmentOnClickListener()
// final Button buttonWriteFile = (Button) view.findViewById(R.id.button_write_file);
// buttonWriteFile.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Sometimes it takes someone outside the box to see why we really need a box at all
// // think about it...
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// buttonWriteFile.setText(R.string.string_challenge_delete_file);
// } else {
// buttonWriteFile.setText(R.string.string_challenge_write_file);
// }
//
// return view;
// }
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengeten.fragments.AboutFragment;
import com.reoky.crackme.challengeten.fragments.ChallengeTenFragment;
import com.reoky.crackme.challengeten.fragments.HintFragment; | package com.reoky.crackme.challengeten.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeTenFragment();
case 1:
return new HintFragment();
default: | // Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
//
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/fragments/ChallengeTenFragment.java
// public class ChallengeTenFragment extends Fragment {
//
// public ChallengeTenFragment() {}
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// final InputMethodManager immy = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// immy.hideSoftInputFromWindow(getView().getWindowToken(), 0);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_challenge_one, container, false);
//
// // Handle the user checking their answer
// final Button buttonCheck = (Button) view.findViewById(R.id.challenge_one_button_check);
// buttonCheck.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Wire button_write_file to ChallengeTenFragmentOnClickListener()
// final Button buttonWriteFile = (Button) view.findViewById(R.id.button_write_file);
// buttonWriteFile.setOnClickListener(new ChallengeTenFragmentOnClickListener());
//
// // Sometimes it takes someone outside the box to see why we really need a box at all
// // think about it...
// File file = view.getContext().getFileStreamPath("ANSWER");
// if (file.exists()) {
// buttonWriteFile.setText(R.string.string_challenge_delete_file);
// } else {
// buttonWriteFile.setText(R.string.string_challenge_write_file);
// }
//
// return view;
// }
// }
// Path: challenge-ten/app/src/main/java/com/reoky/crackme/challengeten/adaptors/ChallengePagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengeten.fragments.AboutFragment;
import com.reoky.crackme.challengeten.fragments.ChallengeTenFragment;
import com.reoky.crackme.challengeten.fragments.HintFragment;
package com.reoky.crackme.challengeten.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeTenFragment();
case 1:
return new HintFragment();
default: | return new AboutFragment(); |
reoky/android-crackme-challenge | challenge-four/app/src/main/java/com/reoky/crackme/challengefour/fragments/ChallengeFourFragment.java | // Path: challenge-four/app/src/main/java/com/reoky/crackme/challengefour/listeners/ChallengeFourFragmentOnClickListener.java
// public class ChallengeFourFragmentOnClickListener implements View.OnClickListener {
//
// private ChallengeFourFragment fragment;
//
// // Since we're not using an anonymous OnClickListener, but rather a named outer OnClickListener
// public ChallengeFourFragmentOnClickListener(ChallengeFourFragment fragment) {
// this.fragment = fragment;
// }
//
// @Override
// public void onClick(View view) {
// View parent = (View) view.getParent().getParent(); // TextGuess is in the parent parent view
// switch (view.getId()) {
// // Check to see whether the phone is in the GPS fenced area
// case R.id.challenge_four_button_check:
// fragment.checkLocation();
// break;
// }
// }
// }
| import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.reoky.crackme.challengefour.R;
import com.reoky.crackme.challengefour.listeners.ChallengeFourFragmentOnClickListener; | package com.reoky.crackme.challengefour.fragments;
public class ChallengeFourFragment extends Fragment implements LocationListener {
public ChallengeFourFragment() {}
// Location
private LocationManager locationManager;
private Context context;
private Location location;
// UI
private TextView textViewLatitude;
private TextView textViewLongitude;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_challenge_four, container, false);
// Handle the user checking their answer
final Button buttonCheck = (Button) view.findViewById(R.id.challenge_four_button_check); | // Path: challenge-four/app/src/main/java/com/reoky/crackme/challengefour/listeners/ChallengeFourFragmentOnClickListener.java
// public class ChallengeFourFragmentOnClickListener implements View.OnClickListener {
//
// private ChallengeFourFragment fragment;
//
// // Since we're not using an anonymous OnClickListener, but rather a named outer OnClickListener
// public ChallengeFourFragmentOnClickListener(ChallengeFourFragment fragment) {
// this.fragment = fragment;
// }
//
// @Override
// public void onClick(View view) {
// View parent = (View) view.getParent().getParent(); // TextGuess is in the parent parent view
// switch (view.getId()) {
// // Check to see whether the phone is in the GPS fenced area
// case R.id.challenge_four_button_check:
// fragment.checkLocation();
// break;
// }
// }
// }
// Path: challenge-four/app/src/main/java/com/reoky/crackme/challengefour/fragments/ChallengeFourFragment.java
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.reoky.crackme.challengefour.R;
import com.reoky.crackme.challengefour.listeners.ChallengeFourFragmentOnClickListener;
package com.reoky.crackme.challengefour.fragments;
public class ChallengeFourFragment extends Fragment implements LocationListener {
public ChallengeFourFragment() {}
// Location
private LocationManager locationManager;
private Context context;
private Location location;
// UI
private TextView textViewLatitude;
private TextView textViewLongitude;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_challenge_four, container, false);
// Handle the user checking their answer
final Button buttonCheck = (Button) view.findViewById(R.id.challenge_four_button_check); | buttonCheck.setOnClickListener(new ChallengeFourFragmentOnClickListener(this)); |
reoky/android-crackme-challenge | challenge-eight/app/src/main/java/com/reoky/crackme/challengeeight/fragments/AboutFragment.java | // Path: challenge-eight/app/src/main/java/com/reoky/crackme/challengeeight/listeners/AboutFragmentOnClickListener.java
// public class AboutFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
// case R.id.button_quit:
// view.setEnabled(false);
// System.exit(0);
// }
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.reoky.crackme.challengeeight.R;
import com.reoky.crackme.challengeeight.listeners.AboutFragmentOnClickListener; | package com.reoky.crackme.challengeeight.fragments;
public class AboutFragment extends Fragment {
public AboutFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the view
View view = inflater.inflate(R.layout.fragment_about, container, false);
// Handle the quit button being pressed
final Button quitButton = (Button) view.findViewById(R.id.button_quit); | // Path: challenge-eight/app/src/main/java/com/reoky/crackme/challengeeight/listeners/AboutFragmentOnClickListener.java
// public class AboutFragmentOnClickListener implements View.OnClickListener {
// @Override
// public void onClick(View view) {
// switch (view.getId()) {
// case R.id.button_quit:
// view.setEnabled(false);
// System.exit(0);
// }
// }
// }
// Path: challenge-eight/app/src/main/java/com/reoky/crackme/challengeeight/fragments/AboutFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.reoky.crackme.challengeeight.R;
import com.reoky.crackme.challengeeight.listeners.AboutFragmentOnClickListener;
package com.reoky.crackme.challengeeight.fragments;
public class AboutFragment extends Fragment {
public AboutFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the view
View view = inflater.inflate(R.layout.fragment_about, container, false);
// Handle the quit button being pressed
final Button quitButton = (Button) view.findViewById(R.id.button_quit); | quitButton.setOnClickListener(new AboutFragmentOnClickListener()); |
reoky/android-crackme-challenge | challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/adaptors/ChallengePagerAdapter.java | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengenine.fragments.AboutFragment;
import com.reoky.crackme.challengenine.fragments.ChallengeNineFragment;
import com.reoky.crackme.challengenine.fragments.HintFragment; | package com.reoky.crackme.challengenine.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeNineFragment();
case 1:
return new HintFragment();
default: | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/fragments/AboutFragment.java
// public class AboutFragment extends Fragment {
//
// public AboutFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
// // Inflate the view
// View view = inflater.inflate(R.layout.fragment_about, container, false);
//
// // Handle the quit button being pressed
// final Button quitButton = (Button) view.findViewById(R.id.button_quit);
// quitButton.setOnClickListener(new AboutFragmentOnClickListener());
//
// return view;
// }
//
// }
// Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/adaptors/ChallengePagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengenine.fragments.AboutFragment;
import com.reoky.crackme.challengenine.fragments.ChallengeNineFragment;
import com.reoky.crackme.challengenine.fragments.HintFragment;
package com.reoky.crackme.challengenine.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeNineFragment();
case 1:
return new HintFragment();
default: | return new AboutFragment(); |
reoky/android-crackme-challenge | challenge-six/app/src/main/java/com/reoky/crackme/challengesix/fragments/HintFragment.java | // Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/listeners/HintFragmentOnCheckedChangeListener.java
// public class HintFragmentOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
// TextView textHint;
//
// public HintFragmentOnCheckedChangeListener(TextView textHint) {
// this.textHint = textHint;
// }
//
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// int newVisibility = isChecked ? View.VISIBLE : View.GONE;
// if (textHint != null) {
// textHint.setVisibility(newVisibility);
// }
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.reoky.crackme.challengesix.R;
import com.reoky.crackme.challengesix.listeners.HintFragmentOnCheckedChangeListener; | package com.reoky.crackme.challengesix.fragments;
public class HintFragment extends Fragment {
public HintFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hint, container, false);
final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint); | // Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/listeners/HintFragmentOnCheckedChangeListener.java
// public class HintFragmentOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
// TextView textHint;
//
// public HintFragmentOnCheckedChangeListener(TextView textHint) {
// this.textHint = textHint;
// }
//
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// int newVisibility = isChecked ? View.VISIBLE : View.GONE;
// if (textHint != null) {
// textHint.setVisibility(newVisibility);
// }
// }
// }
// Path: challenge-six/app/src/main/java/com/reoky/crackme/challengesix/fragments/HintFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.reoky.crackme.challengesix.R;
import com.reoky.crackme.challengesix.listeners.HintFragmentOnCheckedChangeListener;
package com.reoky.crackme.challengesix.fragments;
public class HintFragment extends Fragment {
public HintFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hint, container, false);
final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint); | switchShowHint.setOnCheckedChangeListener(new HintFragmentOnCheckedChangeListener((TextView) view.findViewById(R.id.text_hint))); |
reoky/android-crackme-challenge | challenge-three/app/src/main/java/com/reoky/crackme/challengethree/adaptors/ChallengePagerAdapter.java | // Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/fragments/HintFragment.java
// public class HintFragment extends Fragment {
//
// public HintFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_hint, container, false);
// final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint);
// switchShowHint.setOnCheckedChangeListener(new HintFragmentOnCheckedChangeListener((TextView) view.findViewById(R.id.text_hint)));
// return view;
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengethree.fragments.AboutFragment;
import com.reoky.crackme.challengethree.fragments.ChallengeThreeFragment;
import com.reoky.crackme.challengethree.fragments.HintFragment; | package com.reoky.crackme.challengethree.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeThreeFragment();
case 1: | // Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/fragments/HintFragment.java
// public class HintFragment extends Fragment {
//
// public HintFragment() {}
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_hint, container, false);
// final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint);
// switchShowHint.setOnCheckedChangeListener(new HintFragmentOnCheckedChangeListener((TextView) view.findViewById(R.id.text_hint)));
// return view;
// }
//
// }
// Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/adaptors/ChallengePagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.reoky.crackme.challengethree.fragments.AboutFragment;
import com.reoky.crackme.challengethree.fragments.ChallengeThreeFragment;
import com.reoky.crackme.challengethree.fragments.HintFragment;
package com.reoky.crackme.challengethree.adaptors;
public class ChallengePagerAdapter extends FragmentPagerAdapter {
public ChallengePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChallengeThreeFragment();
case 1: | return new HintFragment(); |
reoky/android-crackme-challenge | challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/activities/ChallengeActivity.java | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/adaptors/ChallengePagerAdapter.java
// public class ChallengePagerAdapter extends FragmentPagerAdapter {
//
// public ChallengePagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// switch (position) {
// case 0:
// return new ChallengeNineFragment();
// case 1:
// return new HintFragment();
// default:
// return new AboutFragment();
// }
// }
//
// @Override
// public int getCount() {
// return 3;
// }
// }
//
// Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/listeners/ChallengeActivityOnPageChangeListener.java
// public class ChallengeActivityOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
//
// ActionBar actionBar;
//
// public ChallengeActivityOnPageChangeListener(ActionBar actionBar){
// this.actionBar = actionBar;
// }
//
// @Override
// public void onPageSelected(int position) {
// actionBar.setSelectedNavigationItem(position);
// }
// }
| import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.reoky.crackme.challengenine.R;
import com.reoky.crackme.challengenine.adaptors.ChallengePagerAdapter;
import com.reoky.crackme.challengenine.listeners.ChallengeActivityOnPageChangeListener; | package com.reoky.crackme.challengenine.activities;
public class ChallengeActivity extends FragmentActivity implements ActionBar.TabListener {
ChallengePagerAdapter mChallengePagerAdapter;
ViewPager mViewPager;
ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge);
mChallengePagerAdapter = new ChallengePagerAdapter(getSupportFragmentManager());
actionBar = getActionBar();
// Configure the action barW
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Configure the ViewPager and attach a
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mChallengePagerAdapter); | // Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/adaptors/ChallengePagerAdapter.java
// public class ChallengePagerAdapter extends FragmentPagerAdapter {
//
// public ChallengePagerAdapter(FragmentManager fm) {
// super(fm);
// }
//
// @Override
// public Fragment getItem(int position) {
// switch (position) {
// case 0:
// return new ChallengeNineFragment();
// case 1:
// return new HintFragment();
// default:
// return new AboutFragment();
// }
// }
//
// @Override
// public int getCount() {
// return 3;
// }
// }
//
// Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/listeners/ChallengeActivityOnPageChangeListener.java
// public class ChallengeActivityOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
//
// ActionBar actionBar;
//
// public ChallengeActivityOnPageChangeListener(ActionBar actionBar){
// this.actionBar = actionBar;
// }
//
// @Override
// public void onPageSelected(int position) {
// actionBar.setSelectedNavigationItem(position);
// }
// }
// Path: challenge-nine/app/src/main/java/com/reoky/crackme/challengenine/activities/ChallengeActivity.java
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.reoky.crackme.challengenine.R;
import com.reoky.crackme.challengenine.adaptors.ChallengePagerAdapter;
import com.reoky.crackme.challengenine.listeners.ChallengeActivityOnPageChangeListener;
package com.reoky.crackme.challengenine.activities;
public class ChallengeActivity extends FragmentActivity implements ActionBar.TabListener {
ChallengePagerAdapter mChallengePagerAdapter;
ViewPager mViewPager;
ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge);
mChallengePagerAdapter = new ChallengePagerAdapter(getSupportFragmentManager());
actionBar = getActionBar();
// Configure the action barW
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Configure the ViewPager and attach a
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mChallengePagerAdapter); | mViewPager.setOnPageChangeListener(new ChallengeActivityOnPageChangeListener(actionBar)); |
reoky/android-crackme-challenge | challenge-five/app/src/main/java/com/reoky/crackme/challengefive/activities/ChallengeActivity.java | // Path: challenge-five/app/src/main/java/com/reoky/crackme/challengefive/listeners/ChallengeActivityOnPageChangeListener.java
// public class ChallengeActivityOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
//
// ActionBar actionBar;
//
// public ChallengeActivityOnPageChangeListener(ActionBar actionBar){
// this.actionBar = actionBar;
// }
//
// @Override
// public void onPageSelected(int position) {
// actionBar.setSelectedNavigationItem(position);
// }
// }
| import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.WindowManager;
import com.reoky.crackme.challengefive.R;
import com.reoky.crackme.challengefive.adaptors.ChallengePagerAdapter;
import com.reoky.crackme.challengefive.listeners.ChallengeActivityOnPageChangeListener; | package com.reoky.crackme.challengefive.activities;
public class ChallengeActivity extends FragmentActivity implements ActionBar.TabListener {
ChallengePagerAdapter mChallengePagerAdapter;
ViewPager mViewPager;
ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge);
mChallengePagerAdapter = new ChallengePagerAdapter(getSupportFragmentManager());
actionBar = getActionBar();
// Configure the action bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Configure the ViewPager and attach a
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mChallengePagerAdapter); | // Path: challenge-five/app/src/main/java/com/reoky/crackme/challengefive/listeners/ChallengeActivityOnPageChangeListener.java
// public class ChallengeActivityOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
//
// ActionBar actionBar;
//
// public ChallengeActivityOnPageChangeListener(ActionBar actionBar){
// this.actionBar = actionBar;
// }
//
// @Override
// public void onPageSelected(int position) {
// actionBar.setSelectedNavigationItem(position);
// }
// }
// Path: challenge-five/app/src/main/java/com/reoky/crackme/challengefive/activities/ChallengeActivity.java
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.ActionBar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.WindowManager;
import com.reoky.crackme.challengefive.R;
import com.reoky.crackme.challengefive.adaptors.ChallengePagerAdapter;
import com.reoky.crackme.challengefive.listeners.ChallengeActivityOnPageChangeListener;
package com.reoky.crackme.challengefive.activities;
public class ChallengeActivity extends FragmentActivity implements ActionBar.TabListener {
ChallengePagerAdapter mChallengePagerAdapter;
ViewPager mViewPager;
ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_challenge);
mChallengePagerAdapter = new ChallengePagerAdapter(getSupportFragmentManager());
actionBar = getActionBar();
// Configure the action bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Configure the ViewPager and attach a
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mChallengePagerAdapter); | mViewPager.setOnPageChangeListener(new ChallengeActivityOnPageChangeListener(actionBar)); |
reoky/android-crackme-challenge | challenge-three/app/src/main/java/com/reoky/crackme/challengethree/fragments/HintFragment.java | // Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/listeners/HintFragmentOnCheckedChangeListener.java
// public class HintFragmentOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
// TextView textHint;
//
// public HintFragmentOnCheckedChangeListener(TextView textHint) {
// this.textHint = textHint;
// }
//
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// int newVisibility = isChecked ? View.VISIBLE : View.GONE;
// if (textHint != null) {
// textHint.setVisibility(newVisibility);
// }
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.reoky.crackme.challengethree.R;
import com.reoky.crackme.challengethree.listeners.HintFragmentOnCheckedChangeListener; | package com.reoky.crackme.challengethree.fragments;
public class HintFragment extends Fragment {
public HintFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hint, container, false);
final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint); | // Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/listeners/HintFragmentOnCheckedChangeListener.java
// public class HintFragmentOnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener {
// TextView textHint;
//
// public HintFragmentOnCheckedChangeListener(TextView textHint) {
// this.textHint = textHint;
// }
//
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// int newVisibility = isChecked ? View.VISIBLE : View.GONE;
// if (textHint != null) {
// textHint.setVisibility(newVisibility);
// }
// }
// }
// Path: challenge-three/app/src/main/java/com/reoky/crackme/challengethree/fragments/HintFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.reoky.crackme.challengethree.R;
import com.reoky.crackme.challengethree.listeners.HintFragmentOnCheckedChangeListener;
package com.reoky.crackme.challengethree.fragments;
public class HintFragment extends Fragment {
public HintFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_hint, container, false);
final ToggleButton switchShowHint = (ToggleButton) view.findViewById(R.id.switch_show_hint); | switchShowHint.setOnCheckedChangeListener(new HintFragmentOnCheckedChangeListener((TextView) view.findViewById(R.id.text_hint))); |
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/query/executor/QueryResultTest.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/B.java
// @Entity
// public class B extends Entidade {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String value;
//
// @OneToOne
// private C c;
//
// public B() {
// }
//
// public B(String value) {
// this.value = value;
// }
//
// public Long getId() {
// return id;
// }
//
// public B setId(Long id) {
// this.id = id;
// return this;
// }
//
// public C getC() {
// return c;
// }
//
// public void setC(C c) {
// this.c = c;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String toString() {
// return "B [id=" + id + ", value=" + value + "]";
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.entities.B; | package org.raidenjpa.query.executor;
public class QueryResultTest {
@Test
public void testSimple() { | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/B.java
// @Entity
// public class B extends Entidade {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String value;
//
// @OneToOne
// private C c;
//
// public B() {
// }
//
// public B(String value) {
// this.value = value;
// }
//
// public Long getId() {
// return id;
// }
//
// public B setId(Long id) {
// this.id = id;
// return this;
// }
//
// public C getC() {
// return c;
// }
//
// public void setC(C c) {
// this.c = c;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String toString() {
// return "B [id=" + id + ", value=" + value + "]";
// }
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/query/executor/QueryResultTest.java
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.entities.B;
package org.raidenjpa.query.executor;
public class QueryResultTest {
@Test
public void testSimple() { | List<A> as = new ArrayList<A>(); |
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/query/executor/QueryResultTest.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/B.java
// @Entity
// public class B extends Entidade {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String value;
//
// @OneToOne
// private C c;
//
// public B() {
// }
//
// public B(String value) {
// this.value = value;
// }
//
// public Long getId() {
// return id;
// }
//
// public B setId(Long id) {
// this.id = id;
// return this;
// }
//
// public C getC() {
// return c;
// }
//
// public void setC(C c) {
// this.c = c;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String toString() {
// return "B [id=" + id + ", value=" + value + "]";
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.entities.B; | package org.raidenjpa.query.executor;
public class QueryResultTest {
@Test
public void testSimple() {
List<A> as = new ArrayList<A>();
as.add(new A("a1"));
as.add(new A("a2"));
QueryResult result = new QueryResult();
result.addFrom("a", as);
Iterator<QueryResultRow> it = result.iterator();
A a1 = (A) it.next().get("a");
A a2 = (A) it.next().get("a");
assertEquals("a1", a1.getStringValue());
assertEquals("a2", a2.getStringValue());
}
@Test
public void testAddFromTwice() {
QueryResult result = new QueryResult();
List<A> as = new ArrayList<A>();
as.add(new A("a1"));
as.add(new A("a2"));
as.add(new A("a3"));
result.addFrom("a", as);
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/B.java
// @Entity
// public class B extends Entidade {
//
// @Id
// @GeneratedValue
// private Long id;
//
// private String value;
//
// @OneToOne
// private C c;
//
// public B() {
// }
//
// public B(String value) {
// this.value = value;
// }
//
// public Long getId() {
// return id;
// }
//
// public B setId(Long id) {
// this.id = id;
// return this;
// }
//
// public C getC() {
// return c;
// }
//
// public void setC(C c) {
// this.c = c;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// public String toString() {
// return "B [id=" + id + ", value=" + value + "]";
// }
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/query/executor/QueryResultTest.java
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.entities.B;
package org.raidenjpa.query.executor;
public class QueryResultTest {
@Test
public void testSimple() {
List<A> as = new ArrayList<A>();
as.add(new A("a1"));
as.add(new A("a2"));
QueryResult result = new QueryResult();
result.addFrom("a", as);
Iterator<QueryResultRow> it = result.iterator();
A a1 = (A) it.next().get("a");
A a2 = (A) it.next().get("a");
assertEquals("a1", a1.getStringValue());
assertEquals("a2", a2.getStringValue());
}
@Test
public void testAddFromTwice() {
QueryResult result = new QueryResult();
List<A> as = new ArrayList<A>();
as.add(new A("a1"));
as.add(new A("a2"));
as.add(new A("a3"));
result.addFrom("a", as);
| List<B> bs = new ArrayList<B>(); |
andreitognolo/raidenjpa | raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
// public class RaidenEntityManagerFactory implements EntityManagerFactory {
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager() {
// return createEntityManager(new HashMap());
// }
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager(Map map) {
// return new RaidenEntityManager();
// }
//
// public Metamodel getMetamodel() {
// throw new NotYetImplementedException();
// }
//
// public boolean isOpen() {
// throw new NotYetImplementedException();
// }
//
// public void close() {
//
// }
//
// public Map<String, Object> getProperties() {
// throw new NotYetImplementedException();
// }
//
// public PersistenceUnitUtil getPersistenceUnitUtil() {
// throw new NotYetImplementedException();
// }
//
// public Cache getCache() {
// throw new NoPlansToImplementException();
// }
//
// public CriteriaBuilder getCriteriaBuilder() {
// throw new NoPlansToImplementException();
// }
// }
| import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.raidenjpa.spec.RaidenEntityManagerFactory;
| package org.raidenjpa.util;
@BadSmell("It is duplicated. We should create a component to this kind of stuff")
public class EntityManagerUtil {
private static List<EntityManager> ems = new ArrayList<EntityManager>();
private static EntityManagerFactory emfHibernate;
private static EntityManagerFactory emfRaiden;
private static TestType testType;
public static EntityManager em() {
EntityManager em = emf().createEntityManager();
ems.add(em);
return em;
}
public static <T> T mergeAndCommit(T t) {
EntityManager em = EntityManagerUtil.em();
em.getTransaction().begin();
t = em.merge(t);
em.getTransaction().commit();
return t;
}
private synchronized static EntityManagerFactory emf() {
if (testType == null) {
throw new RuntimeException("testType not defined");
}
if (testType == TestType.HIBERNATE) {
if (emfHibernate == null) {
emfHibernate = Persistence.createEntityManagerFactory("test-pu");
}
return emfHibernate;
} else if (testType == TestType.RAIDEN) {
if (emfRaiden == null) {
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
// public class RaidenEntityManagerFactory implements EntityManagerFactory {
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager() {
// return createEntityManager(new HashMap());
// }
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager(Map map) {
// return new RaidenEntityManager();
// }
//
// public Metamodel getMetamodel() {
// throw new NotYetImplementedException();
// }
//
// public boolean isOpen() {
// throw new NotYetImplementedException();
// }
//
// public void close() {
//
// }
//
// public Map<String, Object> getProperties() {
// throw new NotYetImplementedException();
// }
//
// public PersistenceUnitUtil getPersistenceUnitUtil() {
// throw new NotYetImplementedException();
// }
//
// public Cache getCache() {
// throw new NoPlansToImplementException();
// }
//
// public CriteriaBuilder getCriteriaBuilder() {
// throw new NoPlansToImplementException();
// }
// }
// Path: raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.raidenjpa.spec.RaidenEntityManagerFactory;
package org.raidenjpa.util;
@BadSmell("It is duplicated. We should create a component to this kind of stuff")
public class EntityManagerUtil {
private static List<EntityManager> ems = new ArrayList<EntityManager>();
private static EntityManagerFactory emfHibernate;
private static EntityManagerFactory emfRaiden;
private static TestType testType;
public static EntityManager em() {
EntityManager em = emf().createEntityManager();
ems.add(em);
return em;
}
public static <T> T mergeAndCommit(T t) {
EntityManager em = EntityManagerUtil.em();
em.getTransaction().begin();
t = em.merge(t);
em.getTransaction().commit();
return t;
}
private synchronized static EntityManagerFactory emf() {
if (testType == null) {
throw new RuntimeException("testType not defined");
}
if (testType == TestType.HIBERNATE) {
if (emfHibernate == null) {
emfHibernate = Persistence.createEntityManagerFactory("test-pu");
}
return emfHibernate;
} else if (testType == TestType.RAIDEN) {
if (emfRaiden == null) {
| emfRaiden = new RaidenEntityManagerFactory();
|
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/util/EntityManagerUtil.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
// public class RaidenEntityManagerFactory implements EntityManagerFactory {
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager() {
// return createEntityManager(new HashMap());
// }
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager(Map map) {
// return new RaidenEntityManager();
// }
//
// public Metamodel getMetamodel() {
// throw new NotYetImplementedException();
// }
//
// public boolean isOpen() {
// throw new NotYetImplementedException();
// }
//
// public void close() {
//
// }
//
// public Map<String, Object> getProperties() {
// throw new NotYetImplementedException();
// }
//
// public PersistenceUnitUtil getPersistenceUnitUtil() {
// throw new NotYetImplementedException();
// }
//
// public Cache getCache() {
// throw new NoPlansToImplementException();
// }
//
// public CriteriaBuilder getCriteriaBuilder() {
// throw new NoPlansToImplementException();
// }
// }
| import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.raidenjpa.spec.RaidenEntityManagerFactory;
| package org.raidenjpa.util;
@BadSmell("Static blocks the ability of run tests in parallel")
public class EntityManagerUtil {
private static List<EntityManager> ems = new ArrayList<EntityManager>();
private static EntityManagerFactory emfHibernate;
private static EntityManagerFactory emfRaiden;
private static TestType testType;
public static EntityManager em() {
EntityManager em = emf().createEntityManager();
ems.add(em);
return em;
}
private synchronized static EntityManagerFactory emf() {
if (testType == null) {
throw new RuntimeException("testType not defined");
}
if (testType == TestType.HIBERNATE) {
if (emfHibernate == null) {
emfHibernate = Persistence.createEntityManagerFactory("test-pu");
}
return emfHibernate;
} else if (testType == TestType.RAIDEN) {
if (emfRaiden == null) {
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
// public class RaidenEntityManagerFactory implements EntityManagerFactory {
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager() {
// return createEntityManager(new HashMap());
// }
//
// @SuppressWarnings("rawtypes")
// public EntityManager createEntityManager(Map map) {
// return new RaidenEntityManager();
// }
//
// public Metamodel getMetamodel() {
// throw new NotYetImplementedException();
// }
//
// public boolean isOpen() {
// throw new NotYetImplementedException();
// }
//
// public void close() {
//
// }
//
// public Map<String, Object> getProperties() {
// throw new NotYetImplementedException();
// }
//
// public PersistenceUnitUtil getPersistenceUnitUtil() {
// throw new NotYetImplementedException();
// }
//
// public Cache getCache() {
// throw new NoPlansToImplementException();
// }
//
// public CriteriaBuilder getCriteriaBuilder() {
// throw new NoPlansToImplementException();
// }
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.raidenjpa.spec.RaidenEntityManagerFactory;
package org.raidenjpa.util;
@BadSmell("Static blocks the ability of run tests in parallel")
public class EntityManagerUtil {
private static List<EntityManager> ems = new ArrayList<EntityManager>();
private static EntityManagerFactory emfHibernate;
private static EntityManagerFactory emfRaiden;
private static TestType testType;
public static EntityManager em() {
EntityManager em = emf().createEntityManager();
ems.add(em);
return em;
}
private synchronized static EntityManagerFactory emf() {
if (testType == null) {
throw new RuntimeException("testType not defined");
}
if (testType == TestType.HIBERNATE) {
if (emfHibernate == null) {
emfHibernate = Persistence.createEntityManagerFactory("test-pu");
}
return emfHibernate;
} else if (testType == TestType.RAIDEN) {
if (emfRaiden == null) {
| emfRaiden = new RaidenEntityManagerFactory();
|
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/parser/QueryWords.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/util/StringUtil.java
// public class StringUtil {
//
// public static boolean equalsIgnoreCase(String value, String ... array) {
// for (String valueInArray: array) {
// if (valueInArray.equalsIgnoreCase(value)) {
// return true;
// }
// }
//
// return false;
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.raidenjpa.util.BadSmell;
import org.raidenjpa.util.StringUtil; | @BadSmell("This should not receive the index")
public String get(int index) {
return words[index];
}
public String current() {
return words[position];
}
public String next() {
return words[position++];
}
public String getJpql() {
return originalJpql;
}
public int length() {
return words.length;
}
public boolean hasMoreWord() {
return length() > position;
}
boolean existAlias() {
if (!hasMoreWord()) {
return false;
}
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/util/StringUtil.java
// public class StringUtil {
//
// public static boolean equalsIgnoreCase(String value, String ... array) {
// for (String valueInArray: array) {
// if (valueInArray.equalsIgnoreCase(value)) {
// return true;
// }
// }
//
// return false;
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/QueryWords.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.raidenjpa.util.BadSmell;
import org.raidenjpa.util.StringUtil;
@BadSmell("This should not receive the index")
public String get(int index) {
return words[index];
}
public String current() {
return words[position];
}
public String next() {
return words[position++];
}
public String getJpql() {
return originalJpql;
}
public int length() {
return words.length;
}
public boolean hasMoreWord() {
return length() > position;
}
boolean existAlias() {
if (!hasMoreWord()) {
return false;
}
| return !StringUtil.equalsIgnoreCase(current(), POSSIBLE_WORDS_AFTER_FROM); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/parser/ConditionSubQuery.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/QueryExecutor.java
// public class QueryExecutor {
//
// private Integer maxResult;
// private int firstResult;
// private Map<String, Object> parameters;
// private QueryParser queryParser;
//
// public QueryExecutor(String jpql, Map<String, Object> parameters, Integer maxResult) {
// this.queryParser = new QueryParser(jpql);
// this.parameters = parameters;
// this.maxResult = maxResult;
// this.firstResult = 0;
// }
//
// public QueryExecutor(QueryParser queryParser, Map<String, Object> parameters) {
// this.queryParser = queryParser;
// this.parameters = parameters;
// }
//
// @FixMe("Which one is the first, group or order?")
// public List<?> getResultList() {
// showJpql();
//
// QueryResult queryResult = new QueryResult();
//
// executeFrom(queryResult);
// executeJoin(queryResult);
// executeWhere(queryResult);
// executeGroup(queryResult);
// executeOrderBy(queryResult);
// executeLimit(queryResult);
//
// return queryResult.getList(queryParser.getSelect(), queryParser.getGroupBy());
// }
//
// private void executeGroup(QueryResult queryResult) {
// if (queryParser.getGroupBy() == null && !queryParser.getSelect().isThereAggregationFunction()) {
// return;
// }
//
// List<List<String>> paths = new ArrayList<List<String>>();
// if (queryParser.getGroupBy() == null) {
// paths.add(Arrays.asList("fake_aggregation_for_group_all_rows"));
// } else {
// for (GroupByElements groupByElements : queryParser.getGroupBy().getElements()) {
// paths.add(groupByElements.getPath());
// }
// }
//
// queryResult.group(paths);
// }
//
// private void showJpql() {
// String jpql = queryParser.getWords().getJpql();
// for (Entry<String, Object> entry : parameters.entrySet()) {
// jpql = jpql.replaceAll(":" + entry.getKey(), entry.getValue().toString());
// }
// }
//
// private void executeOrderBy(QueryResult queryResult) {
// queryResult.sort(queryParser.getOrderBy());
// }
//
// @BadSmell("It is kind of confused. Put it in QueryResult")
// private void executeJoin(QueryResult queryResult) {
// if (queryResult.size() == 0) {
// return;
// }
//
// for (JoinClause join : queryParser.getJoins()) {
// queryResult.join(join, queryParser.getWhere(), parameters);
// }
//
// // @FixMe - There is some case when IN is not equals to JOIN, study it
// for (FromClauseItem item : queryParser.getFrom().getItens()) {
// if (item.isInFrom()) {
// JoinClause join = new JoinClause();
// join.setAlias(item.getAliasName());
// join.setPath(item.getInPath());
// join.setWith(new WithClause());
// queryResult.join(join, queryParser.getWhere(), parameters);
// }
// }
// }
//
// @FixMe("Execute limit before than group by is correct?")
// private void executeLimit(QueryResult queryResult) {
// queryResult.limit(firstResult, maxResult);
// }
//
// private void executeWhere(QueryResult queryResult) {
// if (!queryParser.getWhere().hasElements()) {
// return;
// }
//
// LogicExpressionExecutor logicExpressionExecutor = new LogicExpressionExecutor(queryParser.getWhere().getLogicExpression(), parameters);
//
// Iterator<QueryResultRow> it = queryResult.iterator();
// while(it.hasNext()) {
// QueryResultRow row = it.next();
// if (!logicExpressionExecutor.match(row, true)) {
// it.remove();
// }
// }
// }
//
// @BadSmell("Refactory")
// private void executeFrom(QueryResult queryResult) {
// FromClause from = queryParser.getFrom();
//
// for (FromClauseItem item : from.getItens()) {
// if (!item.isInFrom()) {
// List<Object> rowsInDB = InMemoryDB.me().getAll(item.getClassName());
// queryResult.addFrom(item.getAliasName(), rowsInDB);
// }
// }
// }
//
// public QueryExecutor setFirstResult(int first) {
// this.firstResult = first;
// return this;
// }
// }
| import java.util.List;
import java.util.Map;
import org.raidenjpa.query.executor.QueryExecutor;
import org.raidenjpa.util.FixMe; | do {
word = words.next();
if (word.contains("(")) {
parentheses++;
}
if (word.contains("))")) {
parentheses = parentheses - 2;
} else if (word.contains(")")) {
parentheses--;
}
if (word.equals(",")) {
jpql += word;
} else {
jpql += " " + word;
}
} while(parentheses > 0);
jpql = jpql.substring(1, jpql.length() - 1);
queryParser = new QueryParser(jpql);
if (queryParser.getSelect().getElements().size() > 1) {
throw new RuntimeException("The subquery has more than one value in select: '" + jpql + "'");
}
}
public List<?> getResultList(Map<String, Object> parameters) { | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/QueryExecutor.java
// public class QueryExecutor {
//
// private Integer maxResult;
// private int firstResult;
// private Map<String, Object> parameters;
// private QueryParser queryParser;
//
// public QueryExecutor(String jpql, Map<String, Object> parameters, Integer maxResult) {
// this.queryParser = new QueryParser(jpql);
// this.parameters = parameters;
// this.maxResult = maxResult;
// this.firstResult = 0;
// }
//
// public QueryExecutor(QueryParser queryParser, Map<String, Object> parameters) {
// this.queryParser = queryParser;
// this.parameters = parameters;
// }
//
// @FixMe("Which one is the first, group or order?")
// public List<?> getResultList() {
// showJpql();
//
// QueryResult queryResult = new QueryResult();
//
// executeFrom(queryResult);
// executeJoin(queryResult);
// executeWhere(queryResult);
// executeGroup(queryResult);
// executeOrderBy(queryResult);
// executeLimit(queryResult);
//
// return queryResult.getList(queryParser.getSelect(), queryParser.getGroupBy());
// }
//
// private void executeGroup(QueryResult queryResult) {
// if (queryParser.getGroupBy() == null && !queryParser.getSelect().isThereAggregationFunction()) {
// return;
// }
//
// List<List<String>> paths = new ArrayList<List<String>>();
// if (queryParser.getGroupBy() == null) {
// paths.add(Arrays.asList("fake_aggregation_for_group_all_rows"));
// } else {
// for (GroupByElements groupByElements : queryParser.getGroupBy().getElements()) {
// paths.add(groupByElements.getPath());
// }
// }
//
// queryResult.group(paths);
// }
//
// private void showJpql() {
// String jpql = queryParser.getWords().getJpql();
// for (Entry<String, Object> entry : parameters.entrySet()) {
// jpql = jpql.replaceAll(":" + entry.getKey(), entry.getValue().toString());
// }
// }
//
// private void executeOrderBy(QueryResult queryResult) {
// queryResult.sort(queryParser.getOrderBy());
// }
//
// @BadSmell("It is kind of confused. Put it in QueryResult")
// private void executeJoin(QueryResult queryResult) {
// if (queryResult.size() == 0) {
// return;
// }
//
// for (JoinClause join : queryParser.getJoins()) {
// queryResult.join(join, queryParser.getWhere(), parameters);
// }
//
// // @FixMe - There is some case when IN is not equals to JOIN, study it
// for (FromClauseItem item : queryParser.getFrom().getItens()) {
// if (item.isInFrom()) {
// JoinClause join = new JoinClause();
// join.setAlias(item.getAliasName());
// join.setPath(item.getInPath());
// join.setWith(new WithClause());
// queryResult.join(join, queryParser.getWhere(), parameters);
// }
// }
// }
//
// @FixMe("Execute limit before than group by is correct?")
// private void executeLimit(QueryResult queryResult) {
// queryResult.limit(firstResult, maxResult);
// }
//
// private void executeWhere(QueryResult queryResult) {
// if (!queryParser.getWhere().hasElements()) {
// return;
// }
//
// LogicExpressionExecutor logicExpressionExecutor = new LogicExpressionExecutor(queryParser.getWhere().getLogicExpression(), parameters);
//
// Iterator<QueryResultRow> it = queryResult.iterator();
// while(it.hasNext()) {
// QueryResultRow row = it.next();
// if (!logicExpressionExecutor.match(row, true)) {
// it.remove();
// }
// }
// }
//
// @BadSmell("Refactory")
// private void executeFrom(QueryResult queryResult) {
// FromClause from = queryParser.getFrom();
//
// for (FromClauseItem item : from.getItens()) {
// if (!item.isInFrom()) {
// List<Object> rowsInDB = InMemoryDB.me().getAll(item.getClassName());
// queryResult.addFrom(item.getAliasName(), rowsInDB);
// }
// }
// }
//
// public QueryExecutor setFirstResult(int first) {
// this.firstResult = first;
// return this;
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/ConditionSubQuery.java
import java.util.List;
import java.util.Map;
import org.raidenjpa.query.executor.QueryExecutor;
import org.raidenjpa.util.FixMe;
do {
word = words.next();
if (word.contains("(")) {
parentheses++;
}
if (word.contains("))")) {
parentheses = parentheses - 2;
} else if (word.contains(")")) {
parentheses--;
}
if (word.equals(",")) {
jpql += word;
} else {
jpql += " " + word;
}
} while(parentheses > 0);
jpql = jpql.substring(1, jpql.length() - 1);
queryParser = new QueryParser(jpql);
if (queryParser.getSelect().getElements().size() > 1) {
throw new RuntimeException("The subquery has more than one value in select: '" + jpql + "'");
}
}
public List<?> getResultList(Map<String, Object> parameters) { | QueryExecutor queryExecutor = new QueryExecutor(queryParser, parameters); |
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/BasicTest.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
// @BadSmell("It is duplicated. We should create a component to this kind of stuff")
// public class EntityManagerUtil {
//
// private static List<EntityManager> ems = new ArrayList<EntityManager>();
//
// private static EntityManagerFactory emfHibernate;
//
// private static EntityManagerFactory emfRaiden;
//
// private static TestType testType;
//
// public static EntityManager em() {
// EntityManager em = emf().createEntityManager();
//
// ems.add(em);
//
// return em;
// }
//
// public static <T> T mergeAndCommit(T t) {
// EntityManager em = EntityManagerUtil.em();
// em.getTransaction().begin();
// t = em.merge(t);
// em.getTransaction().commit();
// return t;
// }
//
// private synchronized static EntityManagerFactory emf() {
// if (testType == null) {
// throw new RuntimeException("testType not defined");
// }
//
// if (testType == TestType.HIBERNATE) {
// if (emfHibernate == null) {
// emfHibernate = Persistence.createEntityManagerFactory("test-pu");
// }
// return emfHibernate;
// } else if (testType == TestType.RAIDEN) {
// if (emfRaiden == null) {
// emfRaiden = new RaidenEntityManagerFactory();
// }
// return emfRaiden;
// } else {
// throw new RuntimeException("testType not recognized: " + testType);
// }
// }
//
// public static void clean() {
// for (EntityManager em : ems) {
// try {
// if (em.isOpen()) {
// em.close();
// }
// } catch (RuntimeException e) {
// e.printStackTrace();
// }
// }
//
// ems = new ArrayList<EntityManager>();
//
// testType = null;
// }
//
// public static void asHibernate() {
// testType = TestType.HIBERNATE;
// }
//
// public static boolean isHibernate() {
// return testType == TestType.HIBERNATE;
// }
//
// public static void asRaiden() {
// testType = TestType.RAIDEN;
// }
//
// public static boolean isRaiden() {
// return testType == TestType.RAIDEN;
// }
//
// private enum TestType {
// HIBERNATE, RAIDEN
// }
// }
| import static org.junit.Assert.*;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.util.EntityManagerUtil; | package org.raidenjpa;
public class BasicTest extends AbstractTestCase {
@Test
public void test() {
Service service = new Service();
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
// @BadSmell("It is duplicated. We should create a component to this kind of stuff")
// public class EntityManagerUtil {
//
// private static List<EntityManager> ems = new ArrayList<EntityManager>();
//
// private static EntityManagerFactory emfHibernate;
//
// private static EntityManagerFactory emfRaiden;
//
// private static TestType testType;
//
// public static EntityManager em() {
// EntityManager em = emf().createEntityManager();
//
// ems.add(em);
//
// return em;
// }
//
// public static <T> T mergeAndCommit(T t) {
// EntityManager em = EntityManagerUtil.em();
// em.getTransaction().begin();
// t = em.merge(t);
// em.getTransaction().commit();
// return t;
// }
//
// private synchronized static EntityManagerFactory emf() {
// if (testType == null) {
// throw new RuntimeException("testType not defined");
// }
//
// if (testType == TestType.HIBERNATE) {
// if (emfHibernate == null) {
// emfHibernate = Persistence.createEntityManagerFactory("test-pu");
// }
// return emfHibernate;
// } else if (testType == TestType.RAIDEN) {
// if (emfRaiden == null) {
// emfRaiden = new RaidenEntityManagerFactory();
// }
// return emfRaiden;
// } else {
// throw new RuntimeException("testType not recognized: " + testType);
// }
// }
//
// public static void clean() {
// for (EntityManager em : ems) {
// try {
// if (em.isOpen()) {
// em.close();
// }
// } catch (RuntimeException e) {
// e.printStackTrace();
// }
// }
//
// ems = new ArrayList<EntityManager>();
//
// testType = null;
// }
//
// public static void asHibernate() {
// testType = TestType.HIBERNATE;
// }
//
// public static boolean isHibernate() {
// return testType == TestType.HIBERNATE;
// }
//
// public static void asRaiden() {
// testType = TestType.RAIDEN;
// }
//
// public static boolean isRaiden() {
// return testType == TestType.RAIDEN;
// }
//
// private enum TestType {
// HIBERNATE, RAIDEN
// }
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/BasicTest.java
import static org.junit.Assert.*;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.util.EntityManagerUtil;
package org.raidenjpa;
public class BasicTest extends AbstractTestCase {
@Test
public void test() {
Service service = new Service();
| A a1 = new A("a1"); |
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/BasicTest.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
// @BadSmell("It is duplicated. We should create a component to this kind of stuff")
// public class EntityManagerUtil {
//
// private static List<EntityManager> ems = new ArrayList<EntityManager>();
//
// private static EntityManagerFactory emfHibernate;
//
// private static EntityManagerFactory emfRaiden;
//
// private static TestType testType;
//
// public static EntityManager em() {
// EntityManager em = emf().createEntityManager();
//
// ems.add(em);
//
// return em;
// }
//
// public static <T> T mergeAndCommit(T t) {
// EntityManager em = EntityManagerUtil.em();
// em.getTransaction().begin();
// t = em.merge(t);
// em.getTransaction().commit();
// return t;
// }
//
// private synchronized static EntityManagerFactory emf() {
// if (testType == null) {
// throw new RuntimeException("testType not defined");
// }
//
// if (testType == TestType.HIBERNATE) {
// if (emfHibernate == null) {
// emfHibernate = Persistence.createEntityManagerFactory("test-pu");
// }
// return emfHibernate;
// } else if (testType == TestType.RAIDEN) {
// if (emfRaiden == null) {
// emfRaiden = new RaidenEntityManagerFactory();
// }
// return emfRaiden;
// } else {
// throw new RuntimeException("testType not recognized: " + testType);
// }
// }
//
// public static void clean() {
// for (EntityManager em : ems) {
// try {
// if (em.isOpen()) {
// em.close();
// }
// } catch (RuntimeException e) {
// e.printStackTrace();
// }
// }
//
// ems = new ArrayList<EntityManager>();
//
// testType = null;
// }
//
// public static void asHibernate() {
// testType = TestType.HIBERNATE;
// }
//
// public static boolean isHibernate() {
// return testType == TestType.HIBERNATE;
// }
//
// public static void asRaiden() {
// testType = TestType.RAIDEN;
// }
//
// public static boolean isRaiden() {
// return testType == TestType.RAIDEN;
// }
//
// private enum TestType {
// HIBERNATE, RAIDEN
// }
// }
| import static org.junit.Assert.*;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.util.EntityManagerUtil; | package org.raidenjpa;
public class BasicTest extends AbstractTestCase {
@Test
public void test() {
Service service = new Service();
A a1 = new A("a1");
A a2 = new A("a2");
service.save(a1);
service.save(a2);
List<A> result = service.find("a1");
assertEquals(1, result.size());
assertEquals("a1", result.get(0).getStringValue());
}
class Service {
@SuppressWarnings("unchecked")
List<A> find(String value) {
String jpql = "FROM A a WHERE a.stringValue = :value"; | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
//
// Path: raidenjpa-benchmark/src/test/java/org/raidenjpa/util/EntityManagerUtil.java
// @BadSmell("It is duplicated. We should create a component to this kind of stuff")
// public class EntityManagerUtil {
//
// private static List<EntityManager> ems = new ArrayList<EntityManager>();
//
// private static EntityManagerFactory emfHibernate;
//
// private static EntityManagerFactory emfRaiden;
//
// private static TestType testType;
//
// public static EntityManager em() {
// EntityManager em = emf().createEntityManager();
//
// ems.add(em);
//
// return em;
// }
//
// public static <T> T mergeAndCommit(T t) {
// EntityManager em = EntityManagerUtil.em();
// em.getTransaction().begin();
// t = em.merge(t);
// em.getTransaction().commit();
// return t;
// }
//
// private synchronized static EntityManagerFactory emf() {
// if (testType == null) {
// throw new RuntimeException("testType not defined");
// }
//
// if (testType == TestType.HIBERNATE) {
// if (emfHibernate == null) {
// emfHibernate = Persistence.createEntityManagerFactory("test-pu");
// }
// return emfHibernate;
// } else if (testType == TestType.RAIDEN) {
// if (emfRaiden == null) {
// emfRaiden = new RaidenEntityManagerFactory();
// }
// return emfRaiden;
// } else {
// throw new RuntimeException("testType not recognized: " + testType);
// }
// }
//
// public static void clean() {
// for (EntityManager em : ems) {
// try {
// if (em.isOpen()) {
// em.close();
// }
// } catch (RuntimeException e) {
// e.printStackTrace();
// }
// }
//
// ems = new ArrayList<EntityManager>();
//
// testType = null;
// }
//
// public static void asHibernate() {
// testType = TestType.HIBERNATE;
// }
//
// public static boolean isHibernate() {
// return testType == TestType.HIBERNATE;
// }
//
// public static void asRaiden() {
// testType = TestType.RAIDEN;
// }
//
// public static boolean isRaiden() {
// return testType == TestType.RAIDEN;
// }
//
// private enum TestType {
// HIBERNATE, RAIDEN
// }
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/BasicTest.java
import static org.junit.Assert.*;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.Test;
import org.raidenjpa.entities.A;
import org.raidenjpa.util.EntityManagerUtil;
package org.raidenjpa;
public class BasicTest extends AbstractTestCase {
@Test
public void test() {
Service service = new Service();
A a1 = new A("a1");
A a2 = new A("a2");
service.save(a1);
service.save(a2);
List<A> result = service.find("a1");
assertEquals(1, result.size());
assertEquals("a1", result.get(0).getStringValue());
}
class Service {
@SuppressWarnings("unchecked")
List<A> find(String value) {
String jpql = "FROM A a WHERE a.stringValue = :value"; | Query query = EntityManagerUtil.em().createQuery(jpql); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenTypedQuery.java | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import org.raiden.exception.NotYetImplementedException; | package org.raidenjpa.spec;
public class RaidenTypedQuery<X> implements TypedQuery<X> {
private Query query;
public RaidenTypedQuery(Query query) {
this.query = query;
}
@SuppressWarnings({ "unchecked" })
public List<X> getResultList() {
return query.getResultList();
}
@SuppressWarnings("unchecked")
public X getSingleResult() {
return (X) query.getSingleResult();
}
public TypedQuery<X> setMaxResults(int maxResult) {
query.setMaxResults(maxResult);
return this;
}
public TypedQuery<X> setParameter(String name, Object value) {
query.setParameter(name, value);
return this;
}
public int getFirstResult() {
return query.getFirstResult();
}
public TypedQuery<X> setFirstResult(int startPosition) {
query.setFirstResult(startPosition);
return this;
}
public int executeUpdate() { | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenTypedQuery.java
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import org.raiden.exception.NotYetImplementedException;
package org.raidenjpa.spec;
public class RaidenTypedQuery<X> implements TypedQuery<X> {
private Query query;
public RaidenTypedQuery(Query query) {
this.query = query;
}
@SuppressWarnings({ "unchecked" })
public List<X> getResultList() {
return query.getResultList();
}
@SuppressWarnings("unchecked")
public X getSingleResult() {
return (X) query.getSingleResult();
}
public TypedQuery<X> setMaxResults(int maxResult) {
query.setMaxResults(maxResult);
return this;
}
public TypedQuery<X> setParameter(String name, Object value) {
query.setParameter(name, value);
return this;
}
public int getFirstResult() {
return query.getFirstResult();
}
public TypedQuery<X> setFirstResult(int startPosition) {
query.setFirstResult(startPosition);
return this;
}
public int executeUpdate() { | throw new NotYetImplementedException(); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NoPlansToImplementException.java
// public class NoPlansToImplementException extends RuntimeException {
//
// private static final long serialVersionUID = -7580674590102539938L;
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import org.raiden.exception.NoPlansToImplementException;
import org.raiden.exception.NotYetImplementedException; | package org.raidenjpa.spec;
public class RaidenEntityManagerFactory implements EntityManagerFactory {
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager() {
return createEntityManager(new HashMap());
}
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager(Map map) {
return new RaidenEntityManager();
}
public Metamodel getMetamodel() { | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NoPlansToImplementException.java
// public class NoPlansToImplementException extends RuntimeException {
//
// private static final long serialVersionUID = -7580674590102539938L;
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import org.raiden.exception.NoPlansToImplementException;
import org.raiden.exception.NotYetImplementedException;
package org.raidenjpa.spec;
public class RaidenEntityManagerFactory implements EntityManagerFactory {
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager() {
return createEntityManager(new HashMap());
}
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager(Map map) {
return new RaidenEntityManager();
}
public Metamodel getMetamodel() { | throw new NotYetImplementedException(); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NoPlansToImplementException.java
// public class NoPlansToImplementException extends RuntimeException {
//
// private static final long serialVersionUID = -7580674590102539938L;
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import org.raiden.exception.NoPlansToImplementException;
import org.raiden.exception.NotYetImplementedException; | package org.raidenjpa.spec;
public class RaidenEntityManagerFactory implements EntityManagerFactory {
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager() {
return createEntityManager(new HashMap());
}
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager(Map map) {
return new RaidenEntityManager();
}
public Metamodel getMetamodel() {
throw new NotYetImplementedException();
}
public boolean isOpen() {
throw new NotYetImplementedException();
}
public void close() {
}
public Map<String, Object> getProperties() {
throw new NotYetImplementedException();
}
public PersistenceUnitUtil getPersistenceUnitUtil() {
throw new NotYetImplementedException();
}
public Cache getCache() { | // Path: raidenjpa-core/src/main/java/org/raiden/exception/NoPlansToImplementException.java
// public class NoPlansToImplementException extends RuntimeException {
//
// private static final long serialVersionUID = -7580674590102539938L;
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raiden/exception/NotYetImplementedException.java
// public class NotYetImplementedException extends RuntimeException {
//
// private static final long serialVersionUID = 7845965338955346095L;
//
// private String message;
//
// public NotYetImplementedException() {
//
// }
//
// public NotYetImplementedException(String message) {
// this.message = message;
// }
//
// public String toString() {
// return message;
// }
//
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/spec/RaidenEntityManagerFactory.java
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Cache;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import org.raiden.exception.NoPlansToImplementException;
import org.raiden.exception.NotYetImplementedException;
package org.raidenjpa.spec;
public class RaidenEntityManagerFactory implements EntityManagerFactory {
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager() {
return createEntityManager(new HashMap());
}
@SuppressWarnings("rawtypes")
public EntityManager createEntityManager(Map map) {
return new RaidenEntityManager();
}
public Metamodel getMetamodel() {
throw new NotYetImplementedException();
}
public boolean isOpen() {
throw new NotYetImplementedException();
}
public void close() {
}
public Map<String, Object> getProperties() {
throw new NotYetImplementedException();
}
public PersistenceUnitUtil getPersistenceUnitUtil() {
throw new NotYetImplementedException();
}
public Cache getCache() { | throw new NoPlansToImplementException(); |
andreitognolo/raidenjpa | raidenjpa-core/src/test/java/org/raidenjpa/query/executor/PoolerRowsTest.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A; | package org.raidenjpa.query.executor;
public class PoolerRowsTest {
@Test
public void testAggregateOneColumn() {
List<QueryResultRow> rows;
Collection<QueryResultRow> aggregatedRows;
List<List<String>> paths = new ArrayList<List<String>>();
paths.add(Arrays.asList("a", "stringValue"));
rows = new ArrayList<QueryResultRow>(); | // Path: raidenjpa-core/src/main/java/org/raidenjpa/entities/A.java
// @Entity
// public class A extends Entidade {
//
// private Long id;
//
// private String stringValue;
//
// private Integer intValue;
//
// private B b;
//
// private List<ItemA> itens = new ArrayList<ItemA>();
//
// public A() {
// }
//
// public A(String stringValue, int intValue) {
// this.stringValue = stringValue;
// this.intValue = intValue;
// }
//
// public A(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public void addItem(ItemA item) {
// itens.add(item);
// }
//
// @Id
// @GeneratedValue
// public Long getId() {
// return id;
// }
//
// public A setId(Long id) {
// this.id = id;
// return this;
// }
//
// @OneToOne
// public B getB() {
// return b;
// }
//
// public void setB(B b) {
// this.b = b;
// }
//
// public String getStringValue() {
// return stringValue;
// }
//
// public void setStringValue(String stringValue) {
// this.stringValue = stringValue;
// }
//
// public Integer getIntValue() {
// return intValue;
// }
//
// public void setIntValue(Integer intValue) {
// this.intValue = intValue;
// }
//
// @OneToMany(cascade = CascadeType.ALL, mappedBy = "a")
// public List<ItemA> getItens() {
// return itens;
// }
//
// public A setItens(List<ItemA> itens) {
// this.itens = itens;
// return this;
// }
//
// @Override
// public String toString() {
// return "A [id=" + id + ", stringValue=" + stringValue + ", intValue=" + intValue + ", b.id=" + (b == null ? "" : b.getId()) + "]";
// }
//
// }
// Path: raidenjpa-core/src/test/java/org/raidenjpa/query/executor/PoolerRowsTest.java
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.raidenjpa.entities.A;
package org.raidenjpa.query.executor;
public class PoolerRowsTest {
@Test
public void testAggregateOneColumn() {
List<QueryResultRow> rows;
Collection<QueryResultRow> aggregatedRows;
List<List<String>> paths = new ArrayList<List<String>>();
paths.add(Arrays.asList("a", "stringValue"));
rows = new ArrayList<QueryResultRow>(); | rows.add(new QueryResultRow("a", new A("a1"))); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell; | package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell;
package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
| private LogicExpression logicExpression; |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell; | package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
private LogicExpression logicExpression;
private Map<String, Object> parameters;
public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
| // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell;
package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
private LogicExpression logicExpression;
private Map<String, Object> parameters;
public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
| for (LogicExpressionElement element : logicExpression.getElements()) { |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell; | package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
private LogicExpression logicExpression;
private Map<String, Object> parameters;
public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
for (LogicExpressionElement element : logicExpression.getElements()) {
WhereStackAction action = push(element);
if (action == WhereStackAction.RESOLVE) {
resolve(row, executingWhere);
} else if (action == WhereStackAction.REDUCE) {
reduce(row, executingWhere);
}
}
return getResult();
}
void initStack() {
stack = new Stack<Element>();
}
WhereStackAction push(LogicExpressionElement element) {
stack.push(new Element(element));
if (element.isLogicOperator()) { | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell;
package org.raidenjpa.query.executor;
@BadSmell("Should we put it in LogicExpression")
public class LogicExpressionExecutor {
@BadSmell("It is a field, but match is that one which set it")
private Stack<Element> stack;
private LogicExpression logicExpression;
private Map<String, Object> parameters;
public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
for (LogicExpressionElement element : logicExpression.getElements()) {
WhereStackAction action = push(element);
if (action == WhereStackAction.RESOLVE) {
resolve(row, executingWhere);
} else if (action == WhereStackAction.REDUCE) {
reduce(row, executingWhere);
}
}
return getResult();
}
void initStack() {
stack = new Stack<Element>();
}
WhereStackAction push(LogicExpressionElement element) {
stack.push(new Element(element));
if (element.isLogicOperator()) { | return pushLogicOperator((LogicOperator) element); |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell; | public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
for (LogicExpressionElement element : logicExpression.getElements()) {
WhereStackAction action = push(element);
if (action == WhereStackAction.RESOLVE) {
resolve(row, executingWhere);
} else if (action == WhereStackAction.REDUCE) {
reduce(row, executingWhere);
}
}
return getResult();
}
void initStack() {
stack = new Stack<Element>();
}
WhereStackAction push(LogicExpressionElement element) {
stack.push(new Element(element));
if (element.isLogicOperator()) {
return pushLogicOperator((LogicOperator) element);
} else if (element.isExpression()) { | // Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/Condition.java
// public class Condition extends LogicExpressionElement {
//
// private ConditionElement left;
// private String operator;
// private ConditionElement right;
//
// public Condition(QueryWords words) {
// this.left = ConditionElement.create(words);
// this.operator = words.next();
// this.right = ConditionElement.create(words);
// }
//
// public boolean match(QueryResultRow row, Map<String, Object> parameters, boolean executingWhere) {
// Object leftObject = leftObject(row);
// Object rightObject = rightObject(row, parameters);
//
// // @BadSmell (When we are executing where in join process it could not have this one yet)
// if (leftObject == null || rightObject == null) {
// if (executingWhere) {
// return false;
// } else {
// return true;
// }
// }
//
// return ComparatorUtil.isTrue(leftObject, operator, rightObject);
// }
//
// @BadSmell("1) right and left should be the same thing. 2) literal")
// private Object rightObject(QueryResultRow row, Map<String, Object> parameters) {
// if (right.isParameter()) {
// ConditionParameter conditionParameter = (ConditionParameter) right;
// if (Util.isInteger(conditionParameter.getParameterName())) {
// return new Integer(conditionParameter.getParameterName());
// }
// return parameters.get(conditionParameter.getParameterName());
// } else if (right.isPath()) {
// return row.getObject(((ConditionPath) right).getPath());
// } else if (right.isSubQuery()) {
// return ((ConditionSubQuery) right).getResultList(parameters);
// } else if (right.isNull()) {
// return "NULL";
// } else {
// throw new RuntimeException("Expression is neither parameter nor path nor subQuery");
// }
// }
//
// private Object leftObject(QueryResultRow row) {
// return row.getObject(((ConditionPath) left).getPath());
// }
//
// public boolean isExpression() {
// return true;
// }
//
// public ConditionElement getLeft() {
// return left;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public ConditionElement getRight() {
// return right;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpression.java
// public class LogicExpression {
//
// private List<LogicExpressionElement> elements = new ArrayList<LogicExpressionElement>();
//
// public LogicExpression(QueryWords words) {
// while (words.isThereMoreWhereElements()) {
// addElement(words);
// }
// }
//
// public List<LogicExpressionElement> getElements() {
// return elements;
// }
//
// void addElementExpression(QueryWords words) {
// getElements().add(new Condition(words));
// }
//
// void addElementLogicOperator(QueryWords words) {
// getElements().add(new LogicOperator(words.next()));
// }
//
// @FixMe("Make it be the same to with")
// void addElement(QueryWords words) {
// if (words.isLogicOperator()) {
// addElementLogicOperator(words);
// } else {
// addElementExpression(words);
// }
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicExpressionElement.java
// public abstract class LogicExpressionElement {
//
// public boolean isExpression() {
// return false;
// }
//
// public boolean isLogicOperator() {
// return false;
// }
//
// }
//
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/parser/LogicOperator.java
// public class LogicOperator extends LogicExpressionElement {
//
// private String operator;
//
// public LogicOperator(String operator) {
// this.operator = operator;
// }
//
// public boolean isLogicOperator() {
// return true;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public Boolean evaluate(Boolean firstResult, Boolean secondResult) {
// if ("AND".equalsIgnoreCase(operator)) {
// return firstResult && secondResult;
// } else {
// throw new RuntimeException("Operator " + operator + " not yet implemented");
// }
// }
// }
// Path: raidenjpa-core/src/main/java/org/raidenjpa/query/executor/LogicExpressionExecutor.java
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.raidenjpa.query.parser.Condition;
import org.raidenjpa.query.parser.LogicExpression;
import org.raidenjpa.query.parser.LogicExpressionElement;
import org.raidenjpa.query.parser.LogicOperator;
import org.raidenjpa.util.BadSmell;
public LogicExpressionExecutor(LogicExpression logicExpression, Map<String, Object> parameters) {
this.parameters = parameters;
this.logicExpression = logicExpression;
}
public boolean match(QueryResultRow row, boolean executingWhere) {
initStack();
for (LogicExpressionElement element : logicExpression.getElements()) {
WhereStackAction action = push(element);
if (action == WhereStackAction.RESOLVE) {
resolve(row, executingWhere);
} else if (action == WhereStackAction.REDUCE) {
reduce(row, executingWhere);
}
}
return getResult();
}
void initStack() {
stack = new Stack<Element>();
}
WhereStackAction push(LogicExpressionElement element) {
stack.push(new Element(element));
if (element.isLogicOperator()) {
return pushLogicOperator((LogicOperator) element);
} else if (element.isExpression()) { | return pushExpression((Condition) element); |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/JobInfoTest.java | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
| import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import android.content.ComponentName;
import android.net.Uri;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
import androidx.test.core.app.ApplicationProvider;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat; | package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobInfoTest {
private ComponentName component;
@Before
public void setup() { | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
// Path: library/src/test/java/com/doist/jobschedulercompat/JobInfoTest.java
import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import android.content.ComponentName;
import android.net.Uri;
import android.os.Bundle;
import java.util.concurrent.TimeUnit;
import androidx.test.core.app.ApplicationProvider;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobInfoTest {
private ComponentName component;
@Before
public void setup() { | component = new ComponentName(ApplicationProvider.getApplicationContext(), NoopJobService.class); |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/JobServiceTest.java | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java
// public class NoopAsyncJobService extends JobService {
// public static final String EXTRA_DELAY = "delay";
//
// private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
// private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
//
// @Override
// public boolean onStartJob(final JobParameters params) {
// final int jobId = params.getJobId();
// final ScheduledFuture future = executor.schedule(new Runnable() {
// @Override
// public void run() {
// jobFinished(params, false);
// synchronized (futures) {
// futures.remove(jobId);
// }
// }
// }, Math.max(params.getExtras().getLong(EXTRA_DELAY), 1), TimeUnit.MILLISECONDS);
// synchronized (futures) {
// futures.append(jobId, future);
// }
// return true;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// int jobId = params.getJobId();
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// futures.remove(jobId);
// }
// if (future != null) {
// future.cancel(true);
// }
// return false;
// }
//
// static void waitForJob(int jobId) {
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// }
// try {
// if (future != null) {
// future.get();
// }
// } catch (InterruptedException | ExecutionException e) {
// // Ignore.
// }
// }
//
// static void interruptJobs() {
// SparseArray<ScheduledFuture> currentFutures;
// synchronized (futures) {
// currentFutures = futures.clone();
// futures.clear();
// }
// for (int i = 0; i < currentFutures.size(); i++) {
// currentFutures.valueAt(i).cancel(true);
// }
// }
// }
//
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
| import com.doist.jobschedulercompat.util.NoopAsyncJobService;
import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import android.os.Bundle;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobServiceTest {
private static final int TIMEOUT_MS = 200;
private static final int PARALLEL_COUNT = 1000;
private JobParameters params = new JobParameters(0, PersistableBundle.EMPTY, Bundle.EMPTY, null, null, null, false);
@Test
public void testFinishesSynchronously() {
JobService.Binder binder = | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java
// public class NoopAsyncJobService extends JobService {
// public static final String EXTRA_DELAY = "delay";
//
// private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
// private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
//
// @Override
// public boolean onStartJob(final JobParameters params) {
// final int jobId = params.getJobId();
// final ScheduledFuture future = executor.schedule(new Runnable() {
// @Override
// public void run() {
// jobFinished(params, false);
// synchronized (futures) {
// futures.remove(jobId);
// }
// }
// }, Math.max(params.getExtras().getLong(EXTRA_DELAY), 1), TimeUnit.MILLISECONDS);
// synchronized (futures) {
// futures.append(jobId, future);
// }
// return true;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// int jobId = params.getJobId();
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// futures.remove(jobId);
// }
// if (future != null) {
// future.cancel(true);
// }
// return false;
// }
//
// static void waitForJob(int jobId) {
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// }
// try {
// if (future != null) {
// future.get();
// }
// } catch (InterruptedException | ExecutionException e) {
// // Ignore.
// }
// }
//
// static void interruptJobs() {
// SparseArray<ScheduledFuture> currentFutures;
// synchronized (futures) {
// currentFutures = futures.clone();
// futures.clear();
// }
// for (int i = 0; i < currentFutures.size(); i++) {
// currentFutures.valueAt(i).cancel(true);
// }
// }
// }
//
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
// Path: library/src/test/java/com/doist/jobschedulercompat/JobServiceTest.java
import com.doist.jobschedulercompat.util.NoopAsyncJobService;
import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import android.os.Bundle;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobServiceTest {
private static final int TIMEOUT_MS = 200;
private static final int PARALLEL_COUNT = 1000;
private JobParameters params = new JobParameters(0, PersistableBundle.EMPTY, Bundle.EMPTY, null, null, null, false);
@Test
public void testFinishesSynchronously() {
JobService.Binder binder = | (JobService.Binder) Robolectric.buildService(NoopJobService.class).create().get().onBind(null); |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/JobServiceTest.java | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java
// public class NoopAsyncJobService extends JobService {
// public static final String EXTRA_DELAY = "delay";
//
// private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
// private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
//
// @Override
// public boolean onStartJob(final JobParameters params) {
// final int jobId = params.getJobId();
// final ScheduledFuture future = executor.schedule(new Runnable() {
// @Override
// public void run() {
// jobFinished(params, false);
// synchronized (futures) {
// futures.remove(jobId);
// }
// }
// }, Math.max(params.getExtras().getLong(EXTRA_DELAY), 1), TimeUnit.MILLISECONDS);
// synchronized (futures) {
// futures.append(jobId, future);
// }
// return true;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// int jobId = params.getJobId();
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// futures.remove(jobId);
// }
// if (future != null) {
// future.cancel(true);
// }
// return false;
// }
//
// static void waitForJob(int jobId) {
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// }
// try {
// if (future != null) {
// future.get();
// }
// } catch (InterruptedException | ExecutionException e) {
// // Ignore.
// }
// }
//
// static void interruptJobs() {
// SparseArray<ScheduledFuture> currentFutures;
// synchronized (futures) {
// currentFutures = futures.clone();
// futures.clear();
// }
// for (int i = 0; i < currentFutures.size(); i++) {
// currentFutures.valueAt(i).cancel(true);
// }
// }
// }
//
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
| import com.doist.jobschedulercompat.util.NoopAsyncJobService;
import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import android.os.Bundle;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobServiceTest {
private static final int TIMEOUT_MS = 200;
private static final int PARALLEL_COUNT = 1000;
private JobParameters params = new JobParameters(0, PersistableBundle.EMPTY, Bundle.EMPTY, null, null, null, false);
@Test
public void testFinishesSynchronously() {
JobService.Binder binder =
(JobService.Binder) Robolectric.buildService(NoopJobService.class).create().get().onBind(null);
assertFalse(binder.startJob(params, null));
}
@Test
public void testFinishesAsynchronously() throws InterruptedException {
JobService.Binder binder = | // Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java
// public class NoopAsyncJobService extends JobService {
// public static final String EXTRA_DELAY = "delay";
//
// private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
// private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
//
// @Override
// public boolean onStartJob(final JobParameters params) {
// final int jobId = params.getJobId();
// final ScheduledFuture future = executor.schedule(new Runnable() {
// @Override
// public void run() {
// jobFinished(params, false);
// synchronized (futures) {
// futures.remove(jobId);
// }
// }
// }, Math.max(params.getExtras().getLong(EXTRA_DELAY), 1), TimeUnit.MILLISECONDS);
// synchronized (futures) {
// futures.append(jobId, future);
// }
// return true;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// int jobId = params.getJobId();
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// futures.remove(jobId);
// }
// if (future != null) {
// future.cancel(true);
// }
// return false;
// }
//
// static void waitForJob(int jobId) {
// ScheduledFuture future;
// synchronized (futures) {
// future = futures.get(jobId);
// }
// try {
// if (future != null) {
// future.get();
// }
// } catch (InterruptedException | ExecutionException e) {
// // Ignore.
// }
// }
//
// static void interruptJobs() {
// SparseArray<ScheduledFuture> currentFutures;
// synchronized (futures) {
// currentFutures = futures.clone();
// futures.clear();
// }
// for (int i = 0; i < currentFutures.size(); i++) {
// currentFutures.valueAt(i).cancel(true);
// }
// }
// }
//
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
// public class NoopJobService extends JobService {
// @Override
// public boolean onStartJob(JobParameters params) {
// return false;
// }
//
// @Override
// public boolean onStopJob(JobParameters params) {
// return false;
// }
// }
// Path: library/src/test/java/com/doist/jobschedulercompat/JobServiceTest.java
import com.doist.jobschedulercompat.util.NoopAsyncJobService;
import com.doist.jobschedulercompat.util.NoopJobService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import android.os.Bundle;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package com.doist.jobschedulercompat;
@RunWith(RobolectricTestRunner.class)
public class JobServiceTest {
private static final int TIMEOUT_MS = 200;
private static final int PARALLEL_COUNT = 1000;
private JobParameters params = new JobParameters(0, PersistableBundle.EMPTY, Bundle.EMPTY, null, null, null, false);
@Test
public void testFinishesSynchronously() {
JobService.Binder binder =
(JobService.Binder) Robolectric.buildService(NoopJobService.class).create().get().onBind(null);
assertFalse(binder.startJob(params, null));
}
@Test
public void testFinishesAsynchronously() throws InterruptedException {
JobService.Binder binder = | (JobService.Binder) Robolectric.buildService(NoopAsyncJobService.class).create().get().onBind(null); |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java | // Path: library/src/main/java/com/doist/jobschedulercompat/JobParameters.java
// public class JobParameters {
// private final int jobId;
// private final PersistableBundle extras;
// private final Bundle transientExtras;
// private final Network network;
// private final Uri[] triggeredContentUris;
// private final String[] triggeredContentAuthorities;
// private final boolean overrideDeadlineExpired;
//
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public JobParameters(int jobId, PersistableBundle extras, Bundle transientExtras, Network network,
// Uri[] triggeredContentUris, String[] triggeredContentAuthorities,
// boolean overrideDeadlineExpired) {
// this.jobId = jobId;
// this.extras = extras;
// this.transientExtras = transientExtras;
// this.network = network;
// this.triggeredContentUris = triggeredContentUris;
// this.triggeredContentAuthorities = triggeredContentAuthorities;
// this.overrideDeadlineExpired = overrideDeadlineExpired;
// }
//
// /** @see android.app.job.JobParameters#getJobId() */
// public int getJobId() {
// return jobId;
// }
//
// /** @see android.app.job.JobParameters#getExtras() */
// @NonNull
// public PersistableBundle getExtras() {
// return extras;
// }
//
// /** @see android.app.job.JobParameters#getTransientExtras() */
// @NonNull
// public Bundle getTransientExtras() {
// return transientExtras;
// }
//
// /** @see android.app.job.JobParameters#getNetwork() */
// @RequiresApi(Build.VERSION_CODES.P)
// @Nullable
// public Network getNetwork() {
// return network;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentUris() */
// @Nullable
// public Uri[] getTriggeredContentUris() {
// return triggeredContentUris;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentAuthorities() */
// @Nullable
// public String[] getTriggeredContentAuthorities() {
// return triggeredContentAuthorities;
// }
//
// /** @see android.app.job.JobParameters#isOverrideDeadlineExpired() */
// public boolean isOverrideDeadlineExpired() {
// return overrideDeadlineExpired;
// }
// }
//
// Path: library/src/main/java/com/doist/jobschedulercompat/JobService.java
// public abstract class JobService extends Service {
// private Binder binder;
//
// @NonNull
// @Override
// public final IBinder onBind(Intent intent) {
// if (binder == null) {
// binder = new Binder(this);
// }
// return binder;
// }
//
// /** @see android.app.job.JobService#onStartJob(android.app.job.JobParameters) */
// public abstract boolean onStartJob(JobParameters params);
//
// /** @see android.app.job.JobService#onStopJob(android.app.job.JobParameters) */
// public abstract boolean onStopJob(JobParameters params);
//
// /** @see android.app.job.JobService#jobFinished(android.app.job.JobParameters, boolean) */
// public final void jobFinished(JobParameters params, boolean needsReschedule) {
// if (binder != null) {
// binder.notifyJobFinished(params, needsReschedule);
// }
// }
//
// /**
// * Proxies callbacks between the scheduler job service that is handling the work and the user's {@link JobService}.
// *
// * All scheduler job services bind to this service to proxy their lifecycle. This allows maintaining parity with
// * JobScheduler's API, while hiding implementation details away from the user.
// *
// * Methods are synchronized to prevent race conditions when updating {@link #callbacks}.
// * There are no guarantees on which thread calls {@link #notifyJobFinished(JobParameters, boolean)}.
// */
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public static class Binder extends android.os.Binder {
// private final WeakReference<JobService> serviceRef;
// private final SparseArray<Callback> callbacks;
//
// Binder(JobService service) {
// super();
// this.serviceRef = new WeakReference<>(service);
// this.callbacks = new SparseArray<>(1);
// }
//
// public synchronized boolean startJob(JobParameters params, Callback callback) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.put(params.getJobId(), callback);
// boolean willContinueRunning = service.onStartJob(params);
// if (!willContinueRunning) {
// callbacks.remove(params.getJobId());
// }
// return willContinueRunning;
// } else {
// return false;
// }
// }
//
// public synchronized boolean stopJob(JobParameters params) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.remove(params.getJobId());
// return service.onStopJob(params);
// } else {
// return false;
// }
// }
//
// synchronized void notifyJobFinished(JobParameters params, boolean needsReschedule) {
// Callback callback = callbacks.get(params.getJobId());
// if (callback != null) {
// callbacks.remove(params.getJobId());
// callback.jobFinished(params, needsReschedule);
// }
// }
//
// public interface Callback {
// void jobFinished(JobParameters params, boolean needsReschedule);
// }
// }
// }
| import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobService;
import android.util.SparseArray;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; | package com.doist.jobschedulercompat.util;
public class NoopAsyncJobService extends JobService {
public static final String EXTRA_DELAY = "delay";
private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
@Override | // Path: library/src/main/java/com/doist/jobschedulercompat/JobParameters.java
// public class JobParameters {
// private final int jobId;
// private final PersistableBundle extras;
// private final Bundle transientExtras;
// private final Network network;
// private final Uri[] triggeredContentUris;
// private final String[] triggeredContentAuthorities;
// private final boolean overrideDeadlineExpired;
//
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public JobParameters(int jobId, PersistableBundle extras, Bundle transientExtras, Network network,
// Uri[] triggeredContentUris, String[] triggeredContentAuthorities,
// boolean overrideDeadlineExpired) {
// this.jobId = jobId;
// this.extras = extras;
// this.transientExtras = transientExtras;
// this.network = network;
// this.triggeredContentUris = triggeredContentUris;
// this.triggeredContentAuthorities = triggeredContentAuthorities;
// this.overrideDeadlineExpired = overrideDeadlineExpired;
// }
//
// /** @see android.app.job.JobParameters#getJobId() */
// public int getJobId() {
// return jobId;
// }
//
// /** @see android.app.job.JobParameters#getExtras() */
// @NonNull
// public PersistableBundle getExtras() {
// return extras;
// }
//
// /** @see android.app.job.JobParameters#getTransientExtras() */
// @NonNull
// public Bundle getTransientExtras() {
// return transientExtras;
// }
//
// /** @see android.app.job.JobParameters#getNetwork() */
// @RequiresApi(Build.VERSION_CODES.P)
// @Nullable
// public Network getNetwork() {
// return network;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentUris() */
// @Nullable
// public Uri[] getTriggeredContentUris() {
// return triggeredContentUris;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentAuthorities() */
// @Nullable
// public String[] getTriggeredContentAuthorities() {
// return triggeredContentAuthorities;
// }
//
// /** @see android.app.job.JobParameters#isOverrideDeadlineExpired() */
// public boolean isOverrideDeadlineExpired() {
// return overrideDeadlineExpired;
// }
// }
//
// Path: library/src/main/java/com/doist/jobschedulercompat/JobService.java
// public abstract class JobService extends Service {
// private Binder binder;
//
// @NonNull
// @Override
// public final IBinder onBind(Intent intent) {
// if (binder == null) {
// binder = new Binder(this);
// }
// return binder;
// }
//
// /** @see android.app.job.JobService#onStartJob(android.app.job.JobParameters) */
// public abstract boolean onStartJob(JobParameters params);
//
// /** @see android.app.job.JobService#onStopJob(android.app.job.JobParameters) */
// public abstract boolean onStopJob(JobParameters params);
//
// /** @see android.app.job.JobService#jobFinished(android.app.job.JobParameters, boolean) */
// public final void jobFinished(JobParameters params, boolean needsReschedule) {
// if (binder != null) {
// binder.notifyJobFinished(params, needsReschedule);
// }
// }
//
// /**
// * Proxies callbacks between the scheduler job service that is handling the work and the user's {@link JobService}.
// *
// * All scheduler job services bind to this service to proxy their lifecycle. This allows maintaining parity with
// * JobScheduler's API, while hiding implementation details away from the user.
// *
// * Methods are synchronized to prevent race conditions when updating {@link #callbacks}.
// * There are no guarantees on which thread calls {@link #notifyJobFinished(JobParameters, boolean)}.
// */
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public static class Binder extends android.os.Binder {
// private final WeakReference<JobService> serviceRef;
// private final SparseArray<Callback> callbacks;
//
// Binder(JobService service) {
// super();
// this.serviceRef = new WeakReference<>(service);
// this.callbacks = new SparseArray<>(1);
// }
//
// public synchronized boolean startJob(JobParameters params, Callback callback) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.put(params.getJobId(), callback);
// boolean willContinueRunning = service.onStartJob(params);
// if (!willContinueRunning) {
// callbacks.remove(params.getJobId());
// }
// return willContinueRunning;
// } else {
// return false;
// }
// }
//
// public synchronized boolean stopJob(JobParameters params) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.remove(params.getJobId());
// return service.onStopJob(params);
// } else {
// return false;
// }
// }
//
// synchronized void notifyJobFinished(JobParameters params, boolean needsReschedule) {
// Callback callback = callbacks.get(params.getJobId());
// if (callback != null) {
// callbacks.remove(params.getJobId());
// callback.jobFinished(params, needsReschedule);
// }
// }
//
// public interface Callback {
// void jobFinished(JobParameters params, boolean needsReschedule);
// }
// }
// }
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopAsyncJobService.java
import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobService;
import android.util.SparseArray;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
package com.doist.jobschedulercompat.util;
public class NoopAsyncJobService extends JobService {
public static final String EXTRA_DELAY = "delay";
private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
private static final SparseArray<ScheduledFuture> futures = new SparseArray<>();
@Override | public boolean onStartJob(final JobParameters params) { |
Doist/JobSchedulerCompat | library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java | // Path: library/src/main/java/com/doist/jobschedulercompat/JobParameters.java
// public class JobParameters {
// private final int jobId;
// private final PersistableBundle extras;
// private final Bundle transientExtras;
// private final Network network;
// private final Uri[] triggeredContentUris;
// private final String[] triggeredContentAuthorities;
// private final boolean overrideDeadlineExpired;
//
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public JobParameters(int jobId, PersistableBundle extras, Bundle transientExtras, Network network,
// Uri[] triggeredContentUris, String[] triggeredContentAuthorities,
// boolean overrideDeadlineExpired) {
// this.jobId = jobId;
// this.extras = extras;
// this.transientExtras = transientExtras;
// this.network = network;
// this.triggeredContentUris = triggeredContentUris;
// this.triggeredContentAuthorities = triggeredContentAuthorities;
// this.overrideDeadlineExpired = overrideDeadlineExpired;
// }
//
// /** @see android.app.job.JobParameters#getJobId() */
// public int getJobId() {
// return jobId;
// }
//
// /** @see android.app.job.JobParameters#getExtras() */
// @NonNull
// public PersistableBundle getExtras() {
// return extras;
// }
//
// /** @see android.app.job.JobParameters#getTransientExtras() */
// @NonNull
// public Bundle getTransientExtras() {
// return transientExtras;
// }
//
// /** @see android.app.job.JobParameters#getNetwork() */
// @RequiresApi(Build.VERSION_CODES.P)
// @Nullable
// public Network getNetwork() {
// return network;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentUris() */
// @Nullable
// public Uri[] getTriggeredContentUris() {
// return triggeredContentUris;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentAuthorities() */
// @Nullable
// public String[] getTriggeredContentAuthorities() {
// return triggeredContentAuthorities;
// }
//
// /** @see android.app.job.JobParameters#isOverrideDeadlineExpired() */
// public boolean isOverrideDeadlineExpired() {
// return overrideDeadlineExpired;
// }
// }
//
// Path: library/src/main/java/com/doist/jobschedulercompat/JobService.java
// public abstract class JobService extends Service {
// private Binder binder;
//
// @NonNull
// @Override
// public final IBinder onBind(Intent intent) {
// if (binder == null) {
// binder = new Binder(this);
// }
// return binder;
// }
//
// /** @see android.app.job.JobService#onStartJob(android.app.job.JobParameters) */
// public abstract boolean onStartJob(JobParameters params);
//
// /** @see android.app.job.JobService#onStopJob(android.app.job.JobParameters) */
// public abstract boolean onStopJob(JobParameters params);
//
// /** @see android.app.job.JobService#jobFinished(android.app.job.JobParameters, boolean) */
// public final void jobFinished(JobParameters params, boolean needsReschedule) {
// if (binder != null) {
// binder.notifyJobFinished(params, needsReschedule);
// }
// }
//
// /**
// * Proxies callbacks between the scheduler job service that is handling the work and the user's {@link JobService}.
// *
// * All scheduler job services bind to this service to proxy their lifecycle. This allows maintaining parity with
// * JobScheduler's API, while hiding implementation details away from the user.
// *
// * Methods are synchronized to prevent race conditions when updating {@link #callbacks}.
// * There are no guarantees on which thread calls {@link #notifyJobFinished(JobParameters, boolean)}.
// */
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public static class Binder extends android.os.Binder {
// private final WeakReference<JobService> serviceRef;
// private final SparseArray<Callback> callbacks;
//
// Binder(JobService service) {
// super();
// this.serviceRef = new WeakReference<>(service);
// this.callbacks = new SparseArray<>(1);
// }
//
// public synchronized boolean startJob(JobParameters params, Callback callback) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.put(params.getJobId(), callback);
// boolean willContinueRunning = service.onStartJob(params);
// if (!willContinueRunning) {
// callbacks.remove(params.getJobId());
// }
// return willContinueRunning;
// } else {
// return false;
// }
// }
//
// public synchronized boolean stopJob(JobParameters params) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.remove(params.getJobId());
// return service.onStopJob(params);
// } else {
// return false;
// }
// }
//
// synchronized void notifyJobFinished(JobParameters params, boolean needsReschedule) {
// Callback callback = callbacks.get(params.getJobId());
// if (callback != null) {
// callbacks.remove(params.getJobId());
// callback.jobFinished(params, needsReschedule);
// }
// }
//
// public interface Callback {
// void jobFinished(JobParameters params, boolean needsReschedule);
// }
// }
// }
| import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobService; | package com.doist.jobschedulercompat.util;
public class NoopJobService extends JobService {
@Override | // Path: library/src/main/java/com/doist/jobschedulercompat/JobParameters.java
// public class JobParameters {
// private final int jobId;
// private final PersistableBundle extras;
// private final Bundle transientExtras;
// private final Network network;
// private final Uri[] triggeredContentUris;
// private final String[] triggeredContentAuthorities;
// private final boolean overrideDeadlineExpired;
//
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public JobParameters(int jobId, PersistableBundle extras, Bundle transientExtras, Network network,
// Uri[] triggeredContentUris, String[] triggeredContentAuthorities,
// boolean overrideDeadlineExpired) {
// this.jobId = jobId;
// this.extras = extras;
// this.transientExtras = transientExtras;
// this.network = network;
// this.triggeredContentUris = triggeredContentUris;
// this.triggeredContentAuthorities = triggeredContentAuthorities;
// this.overrideDeadlineExpired = overrideDeadlineExpired;
// }
//
// /** @see android.app.job.JobParameters#getJobId() */
// public int getJobId() {
// return jobId;
// }
//
// /** @see android.app.job.JobParameters#getExtras() */
// @NonNull
// public PersistableBundle getExtras() {
// return extras;
// }
//
// /** @see android.app.job.JobParameters#getTransientExtras() */
// @NonNull
// public Bundle getTransientExtras() {
// return transientExtras;
// }
//
// /** @see android.app.job.JobParameters#getNetwork() */
// @RequiresApi(Build.VERSION_CODES.P)
// @Nullable
// public Network getNetwork() {
// return network;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentUris() */
// @Nullable
// public Uri[] getTriggeredContentUris() {
// return triggeredContentUris;
// }
//
// /** @see android.app.job.JobParameters#getTriggeredContentAuthorities() */
// @Nullable
// public String[] getTriggeredContentAuthorities() {
// return triggeredContentAuthorities;
// }
//
// /** @see android.app.job.JobParameters#isOverrideDeadlineExpired() */
// public boolean isOverrideDeadlineExpired() {
// return overrideDeadlineExpired;
// }
// }
//
// Path: library/src/main/java/com/doist/jobschedulercompat/JobService.java
// public abstract class JobService extends Service {
// private Binder binder;
//
// @NonNull
// @Override
// public final IBinder onBind(Intent intent) {
// if (binder == null) {
// binder = new Binder(this);
// }
// return binder;
// }
//
// /** @see android.app.job.JobService#onStartJob(android.app.job.JobParameters) */
// public abstract boolean onStartJob(JobParameters params);
//
// /** @see android.app.job.JobService#onStopJob(android.app.job.JobParameters) */
// public abstract boolean onStopJob(JobParameters params);
//
// /** @see android.app.job.JobService#jobFinished(android.app.job.JobParameters, boolean) */
// public final void jobFinished(JobParameters params, boolean needsReschedule) {
// if (binder != null) {
// binder.notifyJobFinished(params, needsReschedule);
// }
// }
//
// /**
// * Proxies callbacks between the scheduler job service that is handling the work and the user's {@link JobService}.
// *
// * All scheduler job services bind to this service to proxy their lifecycle. This allows maintaining parity with
// * JobScheduler's API, while hiding implementation details away from the user.
// *
// * Methods are synchronized to prevent race conditions when updating {@link #callbacks}.
// * There are no guarantees on which thread calls {@link #notifyJobFinished(JobParameters, boolean)}.
// */
// @RestrictTo(RestrictTo.Scope.LIBRARY)
// public static class Binder extends android.os.Binder {
// private final WeakReference<JobService> serviceRef;
// private final SparseArray<Callback> callbacks;
//
// Binder(JobService service) {
// super();
// this.serviceRef = new WeakReference<>(service);
// this.callbacks = new SparseArray<>(1);
// }
//
// public synchronized boolean startJob(JobParameters params, Callback callback) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.put(params.getJobId(), callback);
// boolean willContinueRunning = service.onStartJob(params);
// if (!willContinueRunning) {
// callbacks.remove(params.getJobId());
// }
// return willContinueRunning;
// } else {
// return false;
// }
// }
//
// public synchronized boolean stopJob(JobParameters params) {
// JobService service = serviceRef.get();
// if (service != null) {
// callbacks.remove(params.getJobId());
// return service.onStopJob(params);
// } else {
// return false;
// }
// }
//
// synchronized void notifyJobFinished(JobParameters params, boolean needsReschedule) {
// Callback callback = callbacks.get(params.getJobId());
// if (callback != null) {
// callbacks.remove(params.getJobId());
// callback.jobFinished(params, needsReschedule);
// }
// }
//
// public interface Callback {
// void jobFinished(JobParameters params, boolean needsReschedule);
// }
// }
// }
// Path: library/src/test/java/com/doist/jobschedulercompat/util/NoopJobService.java
import com.doist.jobschedulercompat.JobParameters;
import com.doist.jobschedulercompat.JobService;
package com.doist.jobschedulercompat.util;
public class NoopJobService extends JobService {
@Override | public boolean onStartJob(JobParameters params) { |
genomescale/starbeast2 | src/sb2tests/TreeLengthLoggerTest.java | // Path: src/starbeast2/TreeLengthLogger.java
// @Description("Logger to report total length of a tree")
// public class TreeLengthLogger extends CalculationNode implements Loggable, Function {
// final public Input<TreeInterface> treeInput = new Input<>("tree", "tree to report length for.", Validate.REQUIRED);
//
// @Override
// public void initAndValidate() {
// // nothing to do
// }
//
// @Override
// public void init(PrintStream out) {
// final TreeInterface tree = treeInput.get();
// if (getID() == null || getID().matches("\\s*")) {
// out.print(tree.getID() + ".length\t");
// } else {
// out.print(getID() + "\t");
// }
// }
//
// @Override
// public void log(long sample, PrintStream out) {
// final double treeLength = TreeStats.getLength(treeInput.get());
// out.print(treeLength + "\t");
// }
//
// @Override
// public void close(PrintStream out) {
// // nothing to do
// }
//
// @Override
// public int getDimension() {
// return 1;
// }
//
// @Override
// public double getArrayValue() {
// return TreeStats.getLength(treeInput.get());
// }
//
// @Override
// public double getArrayValue(int dim) {
// return TreeStats.getLength(treeInput.get());
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import beast.core.State;
import beast.util.TreeParser;
import starbeast2.TreeLengthLogger; | package sb2tests;
public class TreeLengthLoggerTest {
private String newickTree = "((((a1:0.3,a2:0.3):1.6,(b1:1.8,b2:1.8):0.1):0.5,c1:2.4):0.6,c2:3.0)";
private TreeParser testTree;
final double expectedLength = 12.4;
final double allowedError = 10e-6; | // Path: src/starbeast2/TreeLengthLogger.java
// @Description("Logger to report total length of a tree")
// public class TreeLengthLogger extends CalculationNode implements Loggable, Function {
// final public Input<TreeInterface> treeInput = new Input<>("tree", "tree to report length for.", Validate.REQUIRED);
//
// @Override
// public void initAndValidate() {
// // nothing to do
// }
//
// @Override
// public void init(PrintStream out) {
// final TreeInterface tree = treeInput.get();
// if (getID() == null || getID().matches("\\s*")) {
// out.print(tree.getID() + ".length\t");
// } else {
// out.print(getID() + "\t");
// }
// }
//
// @Override
// public void log(long sample, PrintStream out) {
// final double treeLength = TreeStats.getLength(treeInput.get());
// out.print(treeLength + "\t");
// }
//
// @Override
// public void close(PrintStream out) {
// // nothing to do
// }
//
// @Override
// public int getDimension() {
// return 1;
// }
//
// @Override
// public double getArrayValue() {
// return TreeStats.getLength(treeInput.get());
// }
//
// @Override
// public double getArrayValue(int dim) {
// return TreeStats.getLength(treeInput.get());
// }
// }
// Path: src/sb2tests/TreeLengthLoggerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import beast.core.State;
import beast.util.TreeParser;
import starbeast2.TreeLengthLogger;
package sb2tests;
public class TreeLengthLoggerTest {
private String newickTree = "((((a1:0.3,a2:0.3):1.6,(b1:1.8,b2:1.8):0.1):0.5,c1:2.4):0.6,c2:3.0)";
private TreeParser testTree;
final double expectedLength = 12.4;
final double allowedError = 10e-6; | private TreeLengthLogger treeLengthLogger; |
genomescale/starbeast2 | src/beast/app/beauti/StarBeastTipDatesInputEditor.java | // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
| import java.awt.*;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import beast.app.draw.BEASTObjectInputEditor;
import beast.core.BEASTInterface;
import beast.core.Input;
import beast.core.util.Log;
import beast.evolution.alignment.Taxon;
import beast.evolution.tree.TraitSet;
import starbeast2.SpeciesTree; | package beast.app.beauti;
public class StarBeastTipDatesInputEditor extends BEASTObjectInputEditor {
public StarBeastTipDatesInputEditor(BeautiDoc doc) {
super(doc);
}
private static final long serialVersionUID = 1L;
DateFormat dateFormat = DateFormat.getDateInstance();
@Override
public Class<?> type() { | // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
// Path: src/beast/app/beauti/StarBeastTipDatesInputEditor.java
import java.awt.*;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CellEditorListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import beast.app.draw.BEASTObjectInputEditor;
import beast.core.BEASTInterface;
import beast.core.Input;
import beast.core.util.Log;
import beast.evolution.alignment.Taxon;
import beast.evolution.tree.TraitSet;
import starbeast2.SpeciesTree;
package beast.app.beauti;
public class StarBeastTipDatesInputEditor extends BEASTObjectInputEditor {
public StarBeastTipDatesInputEditor(BeautiDoc doc) {
super(doc);
}
private static final long serialVersionUID = 1L;
DateFormat dateFormat = DateFormat.getDateInstance();
@Override
public Class<?> type() { | return SpeciesTree.class; |
genomescale/starbeast2 | src/beast/app/beauti/StarBeastMorphModelAlignmentProvider.java | // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
//
// Path: src/starbeast2/StarBeastTaxonSet.java
// @Description("A TaxonSet is an ordered set of taxa. The order on the taxa is provided at the time of construction" +
// " either from a list of taxon objects or an alignment.")
// public class StarBeastTaxonSet extends TaxonSet {
// private boolean insideBeauti = false;
//
// @Override
// public void initAndValidate() {
// updateTaxaNames();
// }
//
// private void updateTaxaNames() {
// if (taxaNames == null) {
// taxaNames = new ArrayList<>();
// } else {
// taxaNames.clear();
// }
//
// if (taxonsetInput.get() == null && alignmentInput.get() == null) {
// throw new IllegalArgumentException("Need a taxonset and/or an alignment as input");
// }
//
// if (taxonsetInput.get() != null) {
// for (Taxon t : taxonsetInput.get()) {
// final String taxonName = t.getID();
// taxaNames.add(taxonName);
// }
// }
//
// // Add taxon names in morphology but not in molecular data
// if (alignmentInput.get() != null) {
// for (String taxonName : alignmentInput.get().getTaxaNames()) {
// if (!taxaNames.contains(taxonName)) taxaNames.add(taxonName);
// }
// }
//
// insideBeauti |= taxaNames.contains("Beauti2DummyTaxonSet");
// }
//
// // Hack to get tip dates to update correctly
// @Override
// public List<String> asStringList() {
// if (taxaNames == null) return null;
// if (insideBeauti) updateTaxaNames();
//
// return Collections.unmodifiableList(taxaNames);
// }
// }
| import beast.core.BEASTInterface;
import beast.core.Description;
import beast.evolution.alignment.Alignment;
import java.util.*;
import starbeast2.SpeciesTree;
import starbeast2.StarBeastTaxonSet; | package beast.app.beauti;
@Description("Class for creating new partitions for morphological data to be edited by AlignmentListInputEditor")
public class StarBeastMorphModelAlignmentProvider extends BeautiMorphModelAlignmentProvider {
@Override
public void processAlignment(Alignment alignment, List<BEASTInterface> filteredAlignments, boolean ascertained, BeautiDoc doc) throws Exception { | // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
//
// Path: src/starbeast2/StarBeastTaxonSet.java
// @Description("A TaxonSet is an ordered set of taxa. The order on the taxa is provided at the time of construction" +
// " either from a list of taxon objects or an alignment.")
// public class StarBeastTaxonSet extends TaxonSet {
// private boolean insideBeauti = false;
//
// @Override
// public void initAndValidate() {
// updateTaxaNames();
// }
//
// private void updateTaxaNames() {
// if (taxaNames == null) {
// taxaNames = new ArrayList<>();
// } else {
// taxaNames.clear();
// }
//
// if (taxonsetInput.get() == null && alignmentInput.get() == null) {
// throw new IllegalArgumentException("Need a taxonset and/or an alignment as input");
// }
//
// if (taxonsetInput.get() != null) {
// for (Taxon t : taxonsetInput.get()) {
// final String taxonName = t.getID();
// taxaNames.add(taxonName);
// }
// }
//
// // Add taxon names in morphology but not in molecular data
// if (alignmentInput.get() != null) {
// for (String taxonName : alignmentInput.get().getTaxaNames()) {
// if (!taxaNames.contains(taxonName)) taxaNames.add(taxonName);
// }
// }
//
// insideBeauti |= taxaNames.contains("Beauti2DummyTaxonSet");
// }
//
// // Hack to get tip dates to update correctly
// @Override
// public List<String> asStringList() {
// if (taxaNames == null) return null;
// if (insideBeauti) updateTaxaNames();
//
// return Collections.unmodifiableList(taxaNames);
// }
// }
// Path: src/beast/app/beauti/StarBeastMorphModelAlignmentProvider.java
import beast.core.BEASTInterface;
import beast.core.Description;
import beast.evolution.alignment.Alignment;
import java.util.*;
import starbeast2.SpeciesTree;
import starbeast2.StarBeastTaxonSet;
package beast.app.beauti;
@Description("Class for creating new partitions for morphological data to be edited by AlignmentListInputEditor")
public class StarBeastMorphModelAlignmentProvider extends BeautiMorphModelAlignmentProvider {
@Override
public void processAlignment(Alignment alignment, List<BEASTInterface> filteredAlignments, boolean ascertained, BeautiDoc doc) throws Exception { | StarBeastTaxonSet ts = (StarBeastTaxonSet) doc.pluginmap.get("taxonsuperset"); |
genomescale/starbeast2 | src/beast/app/beauti/StarBeastMorphModelAlignmentProvider.java | // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
//
// Path: src/starbeast2/StarBeastTaxonSet.java
// @Description("A TaxonSet is an ordered set of taxa. The order on the taxa is provided at the time of construction" +
// " either from a list of taxon objects or an alignment.")
// public class StarBeastTaxonSet extends TaxonSet {
// private boolean insideBeauti = false;
//
// @Override
// public void initAndValidate() {
// updateTaxaNames();
// }
//
// private void updateTaxaNames() {
// if (taxaNames == null) {
// taxaNames = new ArrayList<>();
// } else {
// taxaNames.clear();
// }
//
// if (taxonsetInput.get() == null && alignmentInput.get() == null) {
// throw new IllegalArgumentException("Need a taxonset and/or an alignment as input");
// }
//
// if (taxonsetInput.get() != null) {
// for (Taxon t : taxonsetInput.get()) {
// final String taxonName = t.getID();
// taxaNames.add(taxonName);
// }
// }
//
// // Add taxon names in morphology but not in molecular data
// if (alignmentInput.get() != null) {
// for (String taxonName : alignmentInput.get().getTaxaNames()) {
// if (!taxaNames.contains(taxonName)) taxaNames.add(taxonName);
// }
// }
//
// insideBeauti |= taxaNames.contains("Beauti2DummyTaxonSet");
// }
//
// // Hack to get tip dates to update correctly
// @Override
// public List<String> asStringList() {
// if (taxaNames == null) return null;
// if (insideBeauti) updateTaxaNames();
//
// return Collections.unmodifiableList(taxaNames);
// }
// }
| import beast.core.BEASTInterface;
import beast.core.Description;
import beast.evolution.alignment.Alignment;
import java.util.*;
import starbeast2.SpeciesTree;
import starbeast2.StarBeastTaxonSet; | package beast.app.beauti;
@Description("Class for creating new partitions for morphological data to be edited by AlignmentListInputEditor")
public class StarBeastMorphModelAlignmentProvider extends BeautiMorphModelAlignmentProvider {
@Override
public void processAlignment(Alignment alignment, List<BEASTInterface> filteredAlignments, boolean ascertained, BeautiDoc doc) throws Exception {
StarBeastTaxonSet ts = (StarBeastTaxonSet) doc.pluginmap.get("taxonsuperset");
ts.alignmentInput.set(alignment);
ts.initAndValidate();
| // Path: src/starbeast2/SpeciesTree.java
// public class SpeciesTree extends Tree implements SpeciesTreeInterface {
// Map<String, Integer> tipNumberMap;
// Multimap<Integer, String> numberTipMap;
//
// public void initAndValidate() {
// super.initAndValidate();
//
// tipNumberMap = new LinkedHashMap<>();
// numberTipMap = HashMultimap.create();
//
// makeMaps();
// }
//
// public Map<String, Integer> getTipNumberMap() {
// return tipNumberMap;
// }
//
// public Multimap<Integer, String> getNumberTipMap() {
// return numberTipMap;
// }
//
// public void adjustTreeNodeHeights() {
// adjustTreeNodeHeights(root);
// }
// }
//
// Path: src/starbeast2/StarBeastTaxonSet.java
// @Description("A TaxonSet is an ordered set of taxa. The order on the taxa is provided at the time of construction" +
// " either from a list of taxon objects or an alignment.")
// public class StarBeastTaxonSet extends TaxonSet {
// private boolean insideBeauti = false;
//
// @Override
// public void initAndValidate() {
// updateTaxaNames();
// }
//
// private void updateTaxaNames() {
// if (taxaNames == null) {
// taxaNames = new ArrayList<>();
// } else {
// taxaNames.clear();
// }
//
// if (taxonsetInput.get() == null && alignmentInput.get() == null) {
// throw new IllegalArgumentException("Need a taxonset and/or an alignment as input");
// }
//
// if (taxonsetInput.get() != null) {
// for (Taxon t : taxonsetInput.get()) {
// final String taxonName = t.getID();
// taxaNames.add(taxonName);
// }
// }
//
// // Add taxon names in morphology but not in molecular data
// if (alignmentInput.get() != null) {
// for (String taxonName : alignmentInput.get().getTaxaNames()) {
// if (!taxaNames.contains(taxonName)) taxaNames.add(taxonName);
// }
// }
//
// insideBeauti |= taxaNames.contains("Beauti2DummyTaxonSet");
// }
//
// // Hack to get tip dates to update correctly
// @Override
// public List<String> asStringList() {
// if (taxaNames == null) return null;
// if (insideBeauti) updateTaxaNames();
//
// return Collections.unmodifiableList(taxaNames);
// }
// }
// Path: src/beast/app/beauti/StarBeastMorphModelAlignmentProvider.java
import beast.core.BEASTInterface;
import beast.core.Description;
import beast.evolution.alignment.Alignment;
import java.util.*;
import starbeast2.SpeciesTree;
import starbeast2.StarBeastTaxonSet;
package beast.app.beauti;
@Description("Class for creating new partitions for morphological data to be edited by AlignmentListInputEditor")
public class StarBeastMorphModelAlignmentProvider extends BeautiMorphModelAlignmentProvider {
@Override
public void processAlignment(Alignment alignment, List<BEASTInterface> filteredAlignments, boolean ascertained, BeautiDoc doc) throws Exception {
StarBeastTaxonSet ts = (StarBeastTaxonSet) doc.pluginmap.get("taxonsuperset");
ts.alignmentInput.set(alignment);
ts.initAndValidate();
| SpeciesTree st = (SpeciesTree) doc.pluginmap.get("Tree.t:Species"); |
biblik/rcpsp-framework | src/rcpsp/Main.java | // Path: src/plot/MainFrame.java
// public class MainFrame extends JFrame {
//
// private static final long serialVersionUID = 1L;
//
// public MainFrame(Instance instance, Solution solution) throws Exception{
//
// build(instance,solution);
//
// }
//
// private void build(Instance instance, Solution solution) throws Exception {
// setTitle("RCPSPS");
//
// setSize(800, 600);
// setResizable(true);
//
// this.setLocationRelativeTo(null);
//
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
// this.setContentPane(new Panel(instance, solution));
// this.setVisible(true);
// }
// }
| import java.io.IOException;
import plot.MainFrame;
| int objectiveValue = rcpsp.getSolution().getObjectiveValue();
int e = 0;
if (!feasible)
{
e = 1;
}
else
{
if(t > (timeLimit + 1) * 1000)
{
e = 2;
System.err.println("Error: Time limit exeeced !!!");
}
}
System.out.println(filename + ";"+ objectiveValue + ";" + t + ";" + e);
// If verbose, print the error
if(verbose)
{
rcpsp.getSolution().print(System.err);
if(e == 1)
{
System.err.println("Error: There is an error in the solution: "+ rcpsp.getSolution().getError());
}
}
// If graphical visualization, print the value of the constraints
if(graphical)
{
| // Path: src/plot/MainFrame.java
// public class MainFrame extends JFrame {
//
// private static final long serialVersionUID = 1L;
//
// public MainFrame(Instance instance, Solution solution) throws Exception{
//
// build(instance,solution);
//
// }
//
// private void build(Instance instance, Solution solution) throws Exception {
// setTitle("RCPSPS");
//
// setSize(800, 600);
// setResizable(true);
//
// this.setLocationRelativeTo(null);
//
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
// this.setContentPane(new Panel(instance, solution));
// this.setVisible(true);
// }
// }
// Path: src/rcpsp/Main.java
import java.io.IOException;
import plot.MainFrame;
int objectiveValue = rcpsp.getSolution().getObjectiveValue();
int e = 0;
if (!feasible)
{
e = 1;
}
else
{
if(t > (timeLimit + 1) * 1000)
{
e = 2;
System.err.println("Error: Time limit exeeced !!!");
}
}
System.out.println(filename + ";"+ objectiveValue + ";" + t + ";" + e);
// If verbose, print the error
if(verbose)
{
rcpsp.getSolution().print(System.err);
if(e == 1)
{
System.err.println("Error: There is an error in the solution: "+ rcpsp.getSolution().getError());
}
}
// If graphical visualization, print the value of the constraints
if(graphical)
{
| new MainFrame(rcpsp.getInstance(), rcpsp.getSolution());
|
airlift/airlift | http-client/src/main/java/io/airlift/http/client/testing/TestingResponse.java | // Path: http-client/src/main/java/io/airlift/http/client/HttpStatus.java
// public enum HttpStatus
// {
// CONTINUE(100, "Continue"),
// SWITCHING_PROTOCOLS(101, "Switching Protocols"),
// PROCESSING(102, "Processing"),
//
// OK(200, "OK"),
// CREATED(201, "Created"),
// ACCEPTED(202, "Accepted"),
// NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
// NO_CONTENT(204, "No Content"),
// RESET_CONTENT(205, "Reset Content"),
// PARTIAL_CONTENT(206, "Partial Content"),
// MULTI_STATUS(207, "Multi-Status"),
// ALREADY_REPORTED(208, "Already Reported"),
//
// MULTIPLE_CHOICES(300, "Multiple Choices"),
// MOVED_PERMANENTLY(301, "Moved Permanently"),
// FOUND(302, "Found"),
// SEE_OTHER(303, "See Other"),
// NOT_MODIFIED(304, "Not Modified"),
// USE_PROXY(305, "Use Proxy"),
// TEMPORARY_REDIRECT(307, "Temporary Redirect"),
// PERMANENT_REDIRECT(308, "Permanent Redirect"),
//
// BAD_REQUEST(400, "Bad Request"),
// UNAUTHORIZED(401, "Unauthorized"),
// PAYMENT_REQUIRED(402, "Payment Required"),
// FORBIDDEN(403, "Forbidden"),
// NOT_FOUND(404, "Not Found"),
// METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
// NOT_ACCEPTABLE(406, "Not Acceptable"),
// PROXY_AUTHENTIATION_REQUIRED(407, "Proxy Authentication Required"),
// REQUEST_TIMEOUT(408, "Request Timeout"),
// CONFLICT(409, "Conflict"),
// GONE(410, "Gone"),
// LENGTH_REQUIRED(411, "Length Required"),
// PRECONDITION_FAILED(412, "Precondition Failed"),
// REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
// REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
// UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
// REQUEST_RANGE_NOT_SATISFIABLE(416, "Request Range Not Satisfiable"),
// EXPECTATION_FAILED(417, "Expectation Failed"),
// IM_A_TEAPOT(418, "I'm a teapot"),
// ENHANCE_YOUR_CALM(420, "Enhance Your Calm"),
// UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
// LOCKED(423, "Locked"),
// FAILED_DEPENDENCY(424, "Failed Dependency"),
// UPGRADE_REQUIRED(426, "Upgrade Required"),
// PRECONDITION_REQUIRED(428, "Precondition Required"),
// TOO_MANY_REQUESTS(429, "Too Many Requests"),
// REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
// UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),
//
// INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
// NOT_IMPLEMENTED(501, "Not Implemented"),
// BAD_GATEWAY(502, "Bad Gateway"),
// SERVICE_UNAVAILABLE(503, "Service Unavailable"),
// GATEWAY_TIMEOUT(504, "Gateway Timeout"),
// HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
// INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
// LOOP_DETECTED(508, "Loop Detected"),
// BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded"),
// NOT_EXTENDED(510, "Not Extended"),
// NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");
//
// public enum Family
// {
// INFORMATIONAL, SUCCESSFUL, REDIRECTION, CLIENT_ERROR, SERVER_ERROR, OTHER
// }
//
// private final int code;
// private final String reason;
// private final Family family;
//
// HttpStatus(int code, String reason)
// {
// this.code = code;
// this.reason = reason;
// this.family = familyForStatusCode(code);
// }
//
// public int code()
// {
// return code;
// }
//
// public String reason()
// {
// return toString();
// }
//
// public Family family()
// {
// return family;
// }
//
// @Override
// public String toString()
// {
// return reason;
// }
//
// private static final Map<Integer, HttpStatus> httpStatusCodes = buildStatusCodeMap();
//
// private static Map<Integer, HttpStatus> buildStatusCodeMap()
// {
// ImmutableMap.Builder<Integer, HttpStatus> map = ImmutableMap.builder();
// for (HttpStatus status : values()) {
// map.put(status.code(), status);
// }
// return map.build();
// }
//
// public static HttpStatus fromStatusCode(int statusCode)
// {
// return httpStatusCodes.get(statusCode);
// }
//
// public static Family familyForStatusCode(int code)
// {
// switch (code / 100) {
// case 1:
// return Family.INFORMATIONAL;
// case 2:
// return Family.SUCCESSFUL;
// case 3:
// return Family.REDIRECTION;
// case 4:
// return Family.CLIENT_ERROR;
// case 5:
// return Family.SERVER_ERROR;
// default:
// return Family.OTHER;
// }
// }
// }
| import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.CountingInputStream;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import io.airlift.http.client.HeaderName;
import io.airlift.http.client.HttpStatus;
import io.airlift.http.client.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull; | package io.airlift.http.client.testing;
public class TestingResponse
implements Response
{ | // Path: http-client/src/main/java/io/airlift/http/client/HttpStatus.java
// public enum HttpStatus
// {
// CONTINUE(100, "Continue"),
// SWITCHING_PROTOCOLS(101, "Switching Protocols"),
// PROCESSING(102, "Processing"),
//
// OK(200, "OK"),
// CREATED(201, "Created"),
// ACCEPTED(202, "Accepted"),
// NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
// NO_CONTENT(204, "No Content"),
// RESET_CONTENT(205, "Reset Content"),
// PARTIAL_CONTENT(206, "Partial Content"),
// MULTI_STATUS(207, "Multi-Status"),
// ALREADY_REPORTED(208, "Already Reported"),
//
// MULTIPLE_CHOICES(300, "Multiple Choices"),
// MOVED_PERMANENTLY(301, "Moved Permanently"),
// FOUND(302, "Found"),
// SEE_OTHER(303, "See Other"),
// NOT_MODIFIED(304, "Not Modified"),
// USE_PROXY(305, "Use Proxy"),
// TEMPORARY_REDIRECT(307, "Temporary Redirect"),
// PERMANENT_REDIRECT(308, "Permanent Redirect"),
//
// BAD_REQUEST(400, "Bad Request"),
// UNAUTHORIZED(401, "Unauthorized"),
// PAYMENT_REQUIRED(402, "Payment Required"),
// FORBIDDEN(403, "Forbidden"),
// NOT_FOUND(404, "Not Found"),
// METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
// NOT_ACCEPTABLE(406, "Not Acceptable"),
// PROXY_AUTHENTIATION_REQUIRED(407, "Proxy Authentication Required"),
// REQUEST_TIMEOUT(408, "Request Timeout"),
// CONFLICT(409, "Conflict"),
// GONE(410, "Gone"),
// LENGTH_REQUIRED(411, "Length Required"),
// PRECONDITION_FAILED(412, "Precondition Failed"),
// REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
// REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
// UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
// REQUEST_RANGE_NOT_SATISFIABLE(416, "Request Range Not Satisfiable"),
// EXPECTATION_FAILED(417, "Expectation Failed"),
// IM_A_TEAPOT(418, "I'm a teapot"),
// ENHANCE_YOUR_CALM(420, "Enhance Your Calm"),
// UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
// LOCKED(423, "Locked"),
// FAILED_DEPENDENCY(424, "Failed Dependency"),
// UPGRADE_REQUIRED(426, "Upgrade Required"),
// PRECONDITION_REQUIRED(428, "Precondition Required"),
// TOO_MANY_REQUESTS(429, "Too Many Requests"),
// REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
// UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),
//
// INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
// NOT_IMPLEMENTED(501, "Not Implemented"),
// BAD_GATEWAY(502, "Bad Gateway"),
// SERVICE_UNAVAILABLE(503, "Service Unavailable"),
// GATEWAY_TIMEOUT(504, "Gateway Timeout"),
// HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
// INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
// LOOP_DETECTED(508, "Loop Detected"),
// BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded"),
// NOT_EXTENDED(510, "Not Extended"),
// NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");
//
// public enum Family
// {
// INFORMATIONAL, SUCCESSFUL, REDIRECTION, CLIENT_ERROR, SERVER_ERROR, OTHER
// }
//
// private final int code;
// private final String reason;
// private final Family family;
//
// HttpStatus(int code, String reason)
// {
// this.code = code;
// this.reason = reason;
// this.family = familyForStatusCode(code);
// }
//
// public int code()
// {
// return code;
// }
//
// public String reason()
// {
// return toString();
// }
//
// public Family family()
// {
// return family;
// }
//
// @Override
// public String toString()
// {
// return reason;
// }
//
// private static final Map<Integer, HttpStatus> httpStatusCodes = buildStatusCodeMap();
//
// private static Map<Integer, HttpStatus> buildStatusCodeMap()
// {
// ImmutableMap.Builder<Integer, HttpStatus> map = ImmutableMap.builder();
// for (HttpStatus status : values()) {
// map.put(status.code(), status);
// }
// return map.build();
// }
//
// public static HttpStatus fromStatusCode(int statusCode)
// {
// return httpStatusCodes.get(statusCode);
// }
//
// public static Family familyForStatusCode(int code)
// {
// switch (code / 100) {
// case 1:
// return Family.INFORMATIONAL;
// case 2:
// return Family.SUCCESSFUL;
// case 3:
// return Family.REDIRECTION;
// case 4:
// return Family.CLIENT_ERROR;
// case 5:
// return Family.SERVER_ERROR;
// default:
// return Family.OTHER;
// }
// }
// }
// Path: http-client/src/main/java/io/airlift/http/client/testing/TestingResponse.java
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.io.CountingInputStream;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import io.airlift.http.client.HeaderName;
import io.airlift.http.client.HttpStatus;
import io.airlift.http.client.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
package io.airlift.http.client.testing;
public class TestingResponse
implements Response
{ | private final HttpStatus status; |
airlift/airlift | json/src/test/java/io/airlift/json/TestJsonModule.java | // Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
| import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.MoreObjects.toStringHelper;
import static io.airlift.json.JsonBinder.jsonBinder;
import static java.util.Objects.requireNonNull;
import static org.joda.time.DateTimeZone.UTC;
import static org.testng.Assert.assertEquals; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.json;
public class TestJsonModule
{
public static final Car CAR = new Car()
.setMake("BMW")
.setModel("M3")
.setYear(2011)
.setPurchased(new DateTime().withZone(UTC))
.setNotes("sweet!")
.setNameList(superDuper("d*a*i*n"));
private ObjectMapper objectMapper;
@BeforeClass
public void setUp()
throws Exception
{
Injector injector = Guice.createInjector(new JsonModule(),
binder -> { | // Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
// Path: json/src/test/java/io/airlift/json/TestJsonModule.java
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.MoreObjects.toStringHelper;
import static io.airlift.json.JsonBinder.jsonBinder;
import static java.util.Objects.requireNonNull;
import static org.joda.time.DateTimeZone.UTC;
import static org.testng.Assert.assertEquals;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.json;
public class TestJsonModule
{
public static final Car CAR = new Car()
.setMake("BMW")
.setModel("M3")
.setYear(2011)
.setPurchased(new DateTime().withZone(UTC))
.setNotes("sweet!")
.setNameList(superDuper("d*a*i*n"));
private ObjectMapper objectMapper;
@BeforeClass
public void setUp()
throws Exception
{
Injector injector = Guice.createInjector(new JsonModule(),
binder -> { | jsonBinder(binder).addSerializerBinding(SuperDuperNameList.class).toInstance(ToStringSerializer.instance); |
airlift/airlift | node/src/test/java/io/airlift/node/TestAddressSource.java | // Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static String encodeAddressAsHostname(InetAddress inetAddress)
// {
// String ipString = InetAddresses.toAddrString(inetAddress);
// if (inetAddress instanceof Inet4Address) {
// ipString = ipString.replace('.', '-');
// }
// else {
// // v6 addresses contain `:` which isn't legal, also v6 can
// // start with a `:` so we prefix with an `x`
// ipString = "x" + ipString.replace(':', '-');
// }
// return ipString + IP_ENCODED_SUFFIX;
// }
//
// Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static Optional<InetAddress> tryDecodeHostnameToAddress(String hostname)
// {
// if (!hostname.endsWith(IP_ENCODED_SUFFIX)) {
// return Optional.empty();
// }
//
// String ipString = hostname.substring(0, hostname.length() - IP_ENCODED_SUFFIX.length());
// if (ipString.startsWith("x")) {
// ipString = ipString.substring(1).replace('-', ':');
// }
// else {
// ipString = ipString.replace('-', '.');
// }
//
// byte[] address = InetAddresses.forString(ipString).getAddress();
//
// try {
// return Optional.of(InetAddress.getByAddress(hostname, address));
// }
// catch (UnknownHostException e) {
// throw new IllegalArgumentException(e);
// }
// }
| import com.google.common.net.InetAddresses;
import org.testng.annotations.Test;
import java.util.Optional;
import static io.airlift.node.AddressToHostname.encodeAddressAsHostname;
import static io.airlift.node.AddressToHostname.tryDecodeHostnameToAddress;
import static org.testng.Assert.assertEquals; | /*
* 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 io.airlift.node;
public class TestAddressSource
{
@Test
public void testIpEncoding()
{
verifyEncoding("127.0.0.1", "127-0-0-1.ip");
verifyEncoding("1.2.3.4", "1-2-3-4.ip");
verifyEncoding("2001:db8:85a3::8a2e:370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("2001:db8:85a3:0000::8a2e:0370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("::1", "x--1.ip");
}
private static void verifyEncoding(String addressString, String encodedHostname)
{ | // Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static String encodeAddressAsHostname(InetAddress inetAddress)
// {
// String ipString = InetAddresses.toAddrString(inetAddress);
// if (inetAddress instanceof Inet4Address) {
// ipString = ipString.replace('.', '-');
// }
// else {
// // v6 addresses contain `:` which isn't legal, also v6 can
// // start with a `:` so we prefix with an `x`
// ipString = "x" + ipString.replace(':', '-');
// }
// return ipString + IP_ENCODED_SUFFIX;
// }
//
// Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static Optional<InetAddress> tryDecodeHostnameToAddress(String hostname)
// {
// if (!hostname.endsWith(IP_ENCODED_SUFFIX)) {
// return Optional.empty();
// }
//
// String ipString = hostname.substring(0, hostname.length() - IP_ENCODED_SUFFIX.length());
// if (ipString.startsWith("x")) {
// ipString = ipString.substring(1).replace('-', ':');
// }
// else {
// ipString = ipString.replace('-', '.');
// }
//
// byte[] address = InetAddresses.forString(ipString).getAddress();
//
// try {
// return Optional.of(InetAddress.getByAddress(hostname, address));
// }
// catch (UnknownHostException e) {
// throw new IllegalArgumentException(e);
// }
// }
// Path: node/src/test/java/io/airlift/node/TestAddressSource.java
import com.google.common.net.InetAddresses;
import org.testng.annotations.Test;
import java.util.Optional;
import static io.airlift.node.AddressToHostname.encodeAddressAsHostname;
import static io.airlift.node.AddressToHostname.tryDecodeHostnameToAddress;
import static org.testng.Assert.assertEquals;
/*
* 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 io.airlift.node;
public class TestAddressSource
{
@Test
public void testIpEncoding()
{
verifyEncoding("127.0.0.1", "127-0-0-1.ip");
verifyEncoding("1.2.3.4", "1-2-3-4.ip");
verifyEncoding("2001:db8:85a3::8a2e:370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("2001:db8:85a3:0000::8a2e:0370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("::1", "x--1.ip");
}
private static void verifyEncoding(String addressString, String encodedHostname)
{ | assertEquals(encodeAddressAsHostname(InetAddresses.forString(addressString)), encodedHostname); |
airlift/airlift | node/src/test/java/io/airlift/node/TestAddressSource.java | // Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static String encodeAddressAsHostname(InetAddress inetAddress)
// {
// String ipString = InetAddresses.toAddrString(inetAddress);
// if (inetAddress instanceof Inet4Address) {
// ipString = ipString.replace('.', '-');
// }
// else {
// // v6 addresses contain `:` which isn't legal, also v6 can
// // start with a `:` so we prefix with an `x`
// ipString = "x" + ipString.replace(':', '-');
// }
// return ipString + IP_ENCODED_SUFFIX;
// }
//
// Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static Optional<InetAddress> tryDecodeHostnameToAddress(String hostname)
// {
// if (!hostname.endsWith(IP_ENCODED_SUFFIX)) {
// return Optional.empty();
// }
//
// String ipString = hostname.substring(0, hostname.length() - IP_ENCODED_SUFFIX.length());
// if (ipString.startsWith("x")) {
// ipString = ipString.substring(1).replace('-', ':');
// }
// else {
// ipString = ipString.replace('-', '.');
// }
//
// byte[] address = InetAddresses.forString(ipString).getAddress();
//
// try {
// return Optional.of(InetAddress.getByAddress(hostname, address));
// }
// catch (UnknownHostException e) {
// throw new IllegalArgumentException(e);
// }
// }
| import com.google.common.net.InetAddresses;
import org.testng.annotations.Test;
import java.util.Optional;
import static io.airlift.node.AddressToHostname.encodeAddressAsHostname;
import static io.airlift.node.AddressToHostname.tryDecodeHostnameToAddress;
import static org.testng.Assert.assertEquals; | /*
* 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 io.airlift.node;
public class TestAddressSource
{
@Test
public void testIpEncoding()
{
verifyEncoding("127.0.0.1", "127-0-0-1.ip");
verifyEncoding("1.2.3.4", "1-2-3-4.ip");
verifyEncoding("2001:db8:85a3::8a2e:370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("2001:db8:85a3:0000::8a2e:0370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("::1", "x--1.ip");
}
private static void verifyEncoding(String addressString, String encodedHostname)
{
assertEquals(encodeAddressAsHostname(InetAddresses.forString(addressString)), encodedHostname); | // Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static String encodeAddressAsHostname(InetAddress inetAddress)
// {
// String ipString = InetAddresses.toAddrString(inetAddress);
// if (inetAddress instanceof Inet4Address) {
// ipString = ipString.replace('.', '-');
// }
// else {
// // v6 addresses contain `:` which isn't legal, also v6 can
// // start with a `:` so we prefix with an `x`
// ipString = "x" + ipString.replace(':', '-');
// }
// return ipString + IP_ENCODED_SUFFIX;
// }
//
// Path: node/src/main/java/io/airlift/node/AddressToHostname.java
// public static Optional<InetAddress> tryDecodeHostnameToAddress(String hostname)
// {
// if (!hostname.endsWith(IP_ENCODED_SUFFIX)) {
// return Optional.empty();
// }
//
// String ipString = hostname.substring(0, hostname.length() - IP_ENCODED_SUFFIX.length());
// if (ipString.startsWith("x")) {
// ipString = ipString.substring(1).replace('-', ':');
// }
// else {
// ipString = ipString.replace('-', '.');
// }
//
// byte[] address = InetAddresses.forString(ipString).getAddress();
//
// try {
// return Optional.of(InetAddress.getByAddress(hostname, address));
// }
// catch (UnknownHostException e) {
// throw new IllegalArgumentException(e);
// }
// }
// Path: node/src/test/java/io/airlift/node/TestAddressSource.java
import com.google.common.net.InetAddresses;
import org.testng.annotations.Test;
import java.util.Optional;
import static io.airlift.node.AddressToHostname.encodeAddressAsHostname;
import static io.airlift.node.AddressToHostname.tryDecodeHostnameToAddress;
import static org.testng.Assert.assertEquals;
/*
* 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 io.airlift.node;
public class TestAddressSource
{
@Test
public void testIpEncoding()
{
verifyEncoding("127.0.0.1", "127-0-0-1.ip");
verifyEncoding("1.2.3.4", "1-2-3-4.ip");
verifyEncoding("2001:db8:85a3::8a2e:370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("2001:db8:85a3:0000::8a2e:0370:7334", "x2001-db8-85a3--8a2e-370-7334.ip");
verifyEncoding("::1", "x--1.ip");
}
private static void verifyEncoding(String addressString, String encodedHostname)
{
assertEquals(encodeAddressAsHostname(InetAddresses.forString(addressString)), encodedHostname); | assertEquals(tryDecodeHostnameToAddress(encodedHostname), Optional.of(InetAddresses.forString(addressString))); |
airlift/airlift | event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static Set<EventTypeMetadata<?>> getValidEventTypeMetaDataSet(Class<?>... eventClasses)
// {
// ImmutableSet.Builder<EventTypeMetadata<?>> set = ImmutableSet.builder();
// for (Class<?> eventClass : eventClasses) {
// set.add(getValidEventTypeMetadata(eventClass));
// }
// return set.build();
// }
| import com.google.common.collect.ImmutableList;
import io.airlift.event.client.NestedDummyEventClass.NestedPart;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
import static com.google.common.io.ByteStreams.nullOutputStream;
import static io.airlift.event.client.ChainedCircularEventClass.ChainedPart;
import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetaDataSet;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class TestJsonEventWriter
{
private JsonEventWriter eventWriter;
@BeforeClass
public void setup()
throws Exception
{ | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static Set<EventTypeMetadata<?>> getValidEventTypeMetaDataSet(Class<?>... eventClasses)
// {
// ImmutableSet.Builder<EventTypeMetadata<?>> set = ImmutableSet.builder();
// for (Class<?> eventClass : eventClasses) {
// set.add(getValidEventTypeMetadata(eventClass));
// }
// return set.build();
// }
// Path: event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java
import com.google.common.collect.ImmutableList;
import io.airlift.event.client.NestedDummyEventClass.NestedPart;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
import static com.google.common.io.ByteStreams.nullOutputStream;
import static io.airlift.event.client.ChainedCircularEventClass.ChainedPart;
import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetaDataSet;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class TestJsonEventWriter
{
private JsonEventWriter eventWriter;
@BeforeClass
public void setup()
throws Exception
{ | Set<EventTypeMetadata<?>> eventTypes = getValidEventTypeMetaDataSet( |
airlift/airlift | log-manager/src/main/java/io/airlift/log/Logging.java | // Path: configuration/src/main/java/io/airlift/configuration/ConfigurationLoader.java
// public static Map<String, String> loadPropertiesFrom(String path)
// throws IOException
// {
// Properties properties = new Properties();
// try (InputStream inputStream = new FileInputStream(path)) {
// properties.load(inputStream);
// }
//
// return fromProperties(properties).entrySet().stream()
// .collect(toImmutableMap(Entry::getKey, entry -> entry.getValue().trim()));
// }
//
// Path: log-manager/src/main/java/io/airlift/log/SocketMessageOutput.java
// public static BufferedHandler createSocketHandler(HostAndPort hostAndPort, Formatter formatter, ErrorManager errorManager)
// {
// SocketMessageOutput output = new SocketMessageOutput(hostAndPort);
// BufferedHandler handler = new BufferedHandler(output, formatter, errorManager);
// handler.start();
// return handler;
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.net.HostAndPort;
import io.airlift.log.RollingFileMessageOutput.CompressionType;
import io.airlift.units.DataSize;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import static com.google.common.collect.Maps.fromProperties;
import static io.airlift.configuration.ConfigurationLoader.loadPropertiesFrom;
import static io.airlift.configuration.ConfigurationUtils.replaceEnvironmentVariables;
import static io.airlift.log.RollingFileMessageOutput.createRollingFileHandler;
import static io.airlift.log.SocketMessageOutput.createSocketHandler; | ROOT.addHandler(consoleHandler);
}
public synchronized void disableConsole()
{
log.info("Disabling stderr output");
ROOT.removeHandler(consoleHandler);
consoleHandler = null;
}
public void logToFile(boolean legacyLoggerImplementation, String logPath, int maxHistory, DataSize maxFileSize, DataSize maxTotalSize, CompressionType compressionType, Formatter formatter)
{
log.info("Logging to %s", logPath);
Handler handler;
if (legacyLoggerImplementation) {
handler = new LegacyRollingFileHandler(logPath, maxHistory, maxFileSize.toBytes(), formatter);
}
else {
handler = createRollingFileHandler(logPath, maxFileSize, maxTotalSize, compressionType, formatter, new BufferedHandlerErrorManager(stdErr));
}
ROOT.addHandler(handler);
}
private void logToSocket(String logPath, Formatter formatter)
{
if (!logPath.startsWith("tcp://") || logPath.lastIndexOf("/") > 6) {
throw new IllegalArgumentException("LogPath for sockets must begin with tcp:// and not contain any path component.");
}
HostAndPort hostAndPort = HostAndPort.fromString(logPath.replace("tcp://", "")); | // Path: configuration/src/main/java/io/airlift/configuration/ConfigurationLoader.java
// public static Map<String, String> loadPropertiesFrom(String path)
// throws IOException
// {
// Properties properties = new Properties();
// try (InputStream inputStream = new FileInputStream(path)) {
// properties.load(inputStream);
// }
//
// return fromProperties(properties).entrySet().stream()
// .collect(toImmutableMap(Entry::getKey, entry -> entry.getValue().trim()));
// }
//
// Path: log-manager/src/main/java/io/airlift/log/SocketMessageOutput.java
// public static BufferedHandler createSocketHandler(HostAndPort hostAndPort, Formatter formatter, ErrorManager errorManager)
// {
// SocketMessageOutput output = new SocketMessageOutput(hostAndPort);
// BufferedHandler handler = new BufferedHandler(output, formatter, errorManager);
// handler.start();
// return handler;
// }
// Path: log-manager/src/main/java/io/airlift/log/Logging.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.net.HostAndPort;
import io.airlift.log.RollingFileMessageOutput.CompressionType;
import io.airlift.units.DataSize;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import static com.google.common.collect.Maps.fromProperties;
import static io.airlift.configuration.ConfigurationLoader.loadPropertiesFrom;
import static io.airlift.configuration.ConfigurationUtils.replaceEnvironmentVariables;
import static io.airlift.log.RollingFileMessageOutput.createRollingFileHandler;
import static io.airlift.log.SocketMessageOutput.createSocketHandler;
ROOT.addHandler(consoleHandler);
}
public synchronized void disableConsole()
{
log.info("Disabling stderr output");
ROOT.removeHandler(consoleHandler);
consoleHandler = null;
}
public void logToFile(boolean legacyLoggerImplementation, String logPath, int maxHistory, DataSize maxFileSize, DataSize maxTotalSize, CompressionType compressionType, Formatter formatter)
{
log.info("Logging to %s", logPath);
Handler handler;
if (legacyLoggerImplementation) {
handler = new LegacyRollingFileHandler(logPath, maxHistory, maxFileSize.toBytes(), formatter);
}
else {
handler = createRollingFileHandler(logPath, maxFileSize, maxTotalSize, compressionType, formatter, new BufferedHandlerErrorManager(stdErr));
}
ROOT.addHandler(handler);
}
private void logToSocket(String logPath, Formatter formatter)
{
if (!logPath.startsWith("tcp://") || logPath.lastIndexOf("/") > 6) {
throw new IllegalArgumentException("LogPath for sockets must begin with tcp:// and not contain any path component.");
}
HostAndPort hostAndPort = HostAndPort.fromString(logPath.replace("tcp://", "")); | Handler handler = createSocketHandler(hostAndPort, formatter, new BufferedHandlerErrorManager(stdErr)); |
airlift/airlift | log-manager/src/main/java/io/airlift/log/Logging.java | // Path: configuration/src/main/java/io/airlift/configuration/ConfigurationLoader.java
// public static Map<String, String> loadPropertiesFrom(String path)
// throws IOException
// {
// Properties properties = new Properties();
// try (InputStream inputStream = new FileInputStream(path)) {
// properties.load(inputStream);
// }
//
// return fromProperties(properties).entrySet().stream()
// .collect(toImmutableMap(Entry::getKey, entry -> entry.getValue().trim()));
// }
//
// Path: log-manager/src/main/java/io/airlift/log/SocketMessageOutput.java
// public static BufferedHandler createSocketHandler(HostAndPort hostAndPort, Formatter formatter, ErrorManager errorManager)
// {
// SocketMessageOutput output = new SocketMessageOutput(hostAndPort);
// BufferedHandler handler = new BufferedHandler(output, formatter, errorManager);
// handler.start();
// return handler;
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.net.HostAndPort;
import io.airlift.log.RollingFileMessageOutput.CompressionType;
import io.airlift.units.DataSize;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import static com.google.common.collect.Maps.fromProperties;
import static io.airlift.configuration.ConfigurationLoader.loadPropertiesFrom;
import static io.airlift.configuration.ConfigurationUtils.replaceEnvironmentVariables;
import static io.airlift.log.RollingFileMessageOutput.createRollingFileHandler;
import static io.airlift.log.SocketMessageOutput.createSocketHandler; | {
java.util.logging.Logger logger = loggers.remove(loggerName);
if (logger != null) {
logger.setLevel(null);
}
}
public synchronized void setLevel(String loggerName, Level level)
{
loggers.computeIfAbsent(loggerName, java.util.logging.Logger::getLogger)
.setLevel(level.toJulLevel());
}
public Map<String, Level> getAllLevels()
{
ImmutableSortedMap.Builder<String, Level> levels = ImmutableSortedMap.naturalOrder();
for (String loggerName : Collections.list(LogManager.getLogManager().getLoggerNames())) {
java.util.logging.Level level = java.util.logging.Logger.getLogger(loggerName).getLevel();
if (level != null) {
levels.put(loggerName, Level.fromJulLevel(level));
}
}
return levels.build();
}
public void configure(LoggingConfiguration config)
{
Map<String, String> logAnnotations = ImmutableMap.of();
if (config.getLogAnnotationFile() != null) {
try { | // Path: configuration/src/main/java/io/airlift/configuration/ConfigurationLoader.java
// public static Map<String, String> loadPropertiesFrom(String path)
// throws IOException
// {
// Properties properties = new Properties();
// try (InputStream inputStream = new FileInputStream(path)) {
// properties.load(inputStream);
// }
//
// return fromProperties(properties).entrySet().stream()
// .collect(toImmutableMap(Entry::getKey, entry -> entry.getValue().trim()));
// }
//
// Path: log-manager/src/main/java/io/airlift/log/SocketMessageOutput.java
// public static BufferedHandler createSocketHandler(HostAndPort hostAndPort, Formatter formatter, ErrorManager errorManager)
// {
// SocketMessageOutput output = new SocketMessageOutput(hostAndPort);
// BufferedHandler handler = new BufferedHandler(output, formatter, errorManager);
// handler.start();
// return handler;
// }
// Path: log-manager/src/main/java/io/airlift/log/Logging.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.net.HostAndPort;
import io.airlift.log.RollingFileMessageOutput.CompressionType;
import io.airlift.units.DataSize;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import static com.google.common.collect.Maps.fromProperties;
import static io.airlift.configuration.ConfigurationLoader.loadPropertiesFrom;
import static io.airlift.configuration.ConfigurationUtils.replaceEnvironmentVariables;
import static io.airlift.log.RollingFileMessageOutput.createRollingFileHandler;
import static io.airlift.log.SocketMessageOutput.createSocketHandler;
{
java.util.logging.Logger logger = loggers.remove(loggerName);
if (logger != null) {
logger.setLevel(null);
}
}
public synchronized void setLevel(String loggerName, Level level)
{
loggers.computeIfAbsent(loggerName, java.util.logging.Logger::getLogger)
.setLevel(level.toJulLevel());
}
public Map<String, Level> getAllLevels()
{
ImmutableSortedMap.Builder<String, Level> levels = ImmutableSortedMap.naturalOrder();
for (String loggerName : Collections.list(LogManager.getLogManager().getLoggerNames())) {
java.util.logging.Level level = java.util.logging.Logger.getLogger(loggerName).getLevel();
if (level != null) {
levels.put(loggerName, Level.fromJulLevel(level));
}
}
return levels.build();
}
public void configure(LoggingConfiguration config)
{
Map<String, String> logAnnotations = ImmutableMap.of();
if (config.getLogAnnotationFile() != null) {
try { | logAnnotations = replaceEnvironmentVariables(loadPropertiesFrom(config.getLogAnnotationFile())); |
airlift/airlift | event/src/main/java/io/airlift/event/client/EventBinder.java | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static <T> EventTypeMetadata<T> getEventTypeMetadata(Class<T> eventClass)
// {
// return new EventTypeMetadata<>(eventClass, new ArrayList<>(), new HashMap<>(), false);
// }
| import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static io.airlift.event.client.EventTypeMetadata.getEventTypeMetadata;
import static java.util.Objects.requireNonNull; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class EventBinder
{
public static EventBinder eventBinder(Binder binder)
{
return new EventBinder(binder);
}
private final Binder binder;
private EventBinder(Binder binder)
{
this.binder = requireNonNull(binder, "binder is null").skipSources(getClass());
}
public void bindEventClient(Class<?>... types)
{
bindGenericEventClient(types);
}
public void bindGenericEventClient(Class<?>... eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
bindGenericEventClient(ImmutableList.copyOf(eventTypes));
}
public void bindGenericEventClient(List<Class<?>> eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
checkArgument(!eventTypes.isEmpty(), "eventTypes is empty");
Binder sourcedBinder = binder.withSource(getCaller());
Multibinder<EventTypeMetadata<?>> metadataBinder = newSetBinder(binder, new TypeLiteral<EventTypeMetadata<?>>() {});
// Bind event type metadata and bind any errors into Guice
for (Class<?> eventType : eventTypes) { | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static <T> EventTypeMetadata<T> getEventTypeMetadata(Class<T> eventClass)
// {
// return new EventTypeMetadata<>(eventClass, new ArrayList<>(), new HashMap<>(), false);
// }
// Path: event/src/main/java/io/airlift/event/client/EventBinder.java
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.TypeLiteral;
import com.google.inject.multibindings.Multibinder;
import java.util.List;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static io.airlift.event.client.EventTypeMetadata.getEventTypeMetadata;
import static java.util.Objects.requireNonNull;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class EventBinder
{
public static EventBinder eventBinder(Binder binder)
{
return new EventBinder(binder);
}
private final Binder binder;
private EventBinder(Binder binder)
{
this.binder = requireNonNull(binder, "binder is null").skipSources(getClass());
}
public void bindEventClient(Class<?>... types)
{
bindGenericEventClient(types);
}
public void bindGenericEventClient(Class<?>... eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
bindGenericEventClient(ImmutableList.copyOf(eventTypes));
}
public void bindGenericEventClient(List<Class<?>> eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
checkArgument(!eventTypes.isEmpty(), "eventTypes is empty");
Binder sourcedBinder = binder.withSource(getCaller());
Multibinder<EventTypeMetadata<?>> metadataBinder = newSetBinder(binder, new TypeLiteral<EventTypeMetadata<?>>() {});
// Bind event type metadata and bind any errors into Guice
for (Class<?> eventType : eventTypes) { | EventTypeMetadata<?> eventTypeMetadata = getEventTypeMetadata(eventType); |
airlift/airlift | jmx-http/src/main/java/io/airlift/jmx/JmxHttpModule.java | // Path: jaxrs/src/main/java/io/airlift/jaxrs/JaxrsBinder.java
// public static JaxrsBinder jaxrsBinder(Binder binder)
// {
// return new JaxrsBinder(binder);
// }
//
// Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
| import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Module;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularData;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.jmx;
public class JmxHttpModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
| // Path: jaxrs/src/main/java/io/airlift/jaxrs/JaxrsBinder.java
// public static JaxrsBinder jaxrsBinder(Binder binder)
// {
// return new JaxrsBinder(binder);
// }
//
// Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
// Path: jmx-http/src/main/java/io/airlift/jmx/JmxHttpModule.java
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Module;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularData;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.jmx;
public class JmxHttpModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
| jaxrsBinder(binder).bind(MBeanResource.class); |
airlift/airlift | jmx-http/src/main/java/io/airlift/jmx/JmxHttpModule.java | // Path: jaxrs/src/main/java/io/airlift/jaxrs/JaxrsBinder.java
// public static JaxrsBinder jaxrsBinder(Binder binder)
// {
// return new JaxrsBinder(binder);
// }
//
// Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
| import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Module;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularData;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.jmx;
public class JmxHttpModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
jaxrsBinder(binder).bind(MBeanResource.class); | // Path: jaxrs/src/main/java/io/airlift/jaxrs/JaxrsBinder.java
// public static JaxrsBinder jaxrsBinder(Binder binder)
// {
// return new JaxrsBinder(binder);
// }
//
// Path: json/src/main/java/io/airlift/json/JsonBinder.java
// public static JsonBinder jsonBinder(Binder binder)
// {
// return new JsonBinder(binder);
// }
// Path: jmx-http/src/main/java/io/airlift/jmx/JmxHttpModule.java
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Module;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularData;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.jmx;
public class JmxHttpModule
implements Module
{
@Override
public void configure(Binder binder)
{
binder.disableCircularProxies();
jaxrsBinder(binder).bind(MBeanResource.class); | jsonBinder(binder).addSerializerBinding(InetAddress.class).toInstance(ToStringSerializer.instance); |
airlift/airlift | event/src/main/java/io/airlift/event/client/JsonEventSerializer.java | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static Set<EventTypeMetadata<?>> getValidEventTypeMetaDataSet(Class<?>... eventClasses)
// {
// ImmutableSet.Builder<EventTypeMetadata<?>> set = ImmutableSet.builder();
// for (Class<?> eventClass : eventClasses) {
// set.add(getValidEventTypeMetadata(eventClass));
// }
// return set.build();
// }
| import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.google.common.collect.ImmutableMap;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetaDataSet;
import static java.util.Objects.requireNonNull; | /*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class JsonEventSerializer
{
private final Map<Class<?>, JsonSerializer<?>> serializers;
@Inject
public JsonEventSerializer(Set<EventTypeMetadata<?>> eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
ImmutableMap.Builder<Class<?>, JsonSerializer<?>> map = ImmutableMap.builder();
for (EventTypeMetadata<?> eventType : eventTypes) {
map.put(eventType.getEventClass(), new EventJsonSerializer<>(eventType));
}
this.serializers = map.build();
}
public JsonEventSerializer(Class<?>... eventClasses)
{ | // Path: event/src/main/java/io/airlift/event/client/EventTypeMetadata.java
// public static Set<EventTypeMetadata<?>> getValidEventTypeMetaDataSet(Class<?>... eventClasses)
// {
// ImmutableSet.Builder<EventTypeMetadata<?>> set = ImmutableSet.builder();
// for (Class<?> eventClass : eventClasses) {
// set.add(getValidEventTypeMetadata(eventClass));
// }
// return set.build();
// }
// Path: event/src/main/java/io/airlift/event/client/JsonEventSerializer.java
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.google.common.collect.ImmutableMap;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetaDataSet;
import static java.util.Objects.requireNonNull;
/*
* Copyright 2010 Proofpoint, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.airlift.event.client;
public class JsonEventSerializer
{
private final Map<Class<?>, JsonSerializer<?>> serializers;
@Inject
public JsonEventSerializer(Set<EventTypeMetadata<?>> eventTypes)
{
requireNonNull(eventTypes, "eventTypes is null");
ImmutableMap.Builder<Class<?>, JsonSerializer<?>> map = ImmutableMap.builder();
for (EventTypeMetadata<?> eventType : eventTypes) {
map.put(eventType.getEventClass(), new EventJsonSerializer<>(eventType));
}
this.serializers = map.build();
}
public JsonEventSerializer(Class<?>... eventClasses)
{ | this(getValidEventTypeMetaDataSet(eventClasses)); |
airlift/airlift | http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java | // Path: testing/src/main/java/io/airlift/testing/Closeables.java
// public static void closeAll(Closeable... closeables)
// throws IOException
// {
// try {
// closeAll((AutoCloseable[]) closeables);
// }
// catch (Exception e) {
// propagateIfPossible(e, IOException.class);
// // Unreachable
// throw new RuntimeException(e);
// }
// }
| import io.airlift.node.NodeConfig;
import io.airlift.node.NodeInfo;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URI;
import java.util.Optional;
import static io.airlift.testing.Closeables.closeAll;
import static org.testng.Assert.assertEquals; |
HttpServerConfig serverConfig = new HttpServerConfig();
serverConfig.setHttpEnabled(true);
serverConfig.setHttpPort(0);
serverConfig.setHttpsEnabled(true);
serverConfig.setAdminEnabled(true);
HttpsConfig httpsConfig = new HttpsConfig()
.setHttpsPort(0);
HttpServerInfo httpServerInfo = new HttpServerInfo(serverConfig, Optional.ofNullable(httpsConfig), nodeInfo);
int httpPort = httpServerInfo.getHttpUri().getPort();
assertEquals(httpServerInfo.getHttpUri(), new URI("http://[::1]:" + httpPort));
assertEquals(httpServerInfo.getHttpExternalUri(), new URI("http://[2001:db8::2:1]:" + httpPort));
int httpsPort = httpServerInfo.getHttpsUri().getPort();
assertEquals(httpServerInfo.getHttpsUri(), new URI("https://[::1]:" + httpsPort));
assertEquals(httpServerInfo.getHttpsExternalUri(), new URI("https://[2001:db8::2:1]:" + httpsPort));
int adminPort = httpServerInfo.getAdminUri().getPort();
assertEquals(httpServerInfo.getAdminUri(), new URI("https://[::1]:" + adminPort));
assertEquals(httpServerInfo.getAdminExternalUri(), new URI("https://[2001:db8::2:1]:" + adminPort));
closeChannels(httpServerInfo);
}
static void closeChannels(HttpServerInfo info)
throws IOException
{ | // Path: testing/src/main/java/io/airlift/testing/Closeables.java
// public static void closeAll(Closeable... closeables)
// throws IOException
// {
// try {
// closeAll((AutoCloseable[]) closeables);
// }
// catch (Exception e) {
// propagateIfPossible(e, IOException.class);
// // Unreachable
// throw new RuntimeException(e);
// }
// }
// Path: http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java
import io.airlift.node.NodeConfig;
import io.airlift.node.NodeInfo;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.URI;
import java.util.Optional;
import static io.airlift.testing.Closeables.closeAll;
import static org.testng.Assert.assertEquals;
HttpServerConfig serverConfig = new HttpServerConfig();
serverConfig.setHttpEnabled(true);
serverConfig.setHttpPort(0);
serverConfig.setHttpsEnabled(true);
serverConfig.setAdminEnabled(true);
HttpsConfig httpsConfig = new HttpsConfig()
.setHttpsPort(0);
HttpServerInfo httpServerInfo = new HttpServerInfo(serverConfig, Optional.ofNullable(httpsConfig), nodeInfo);
int httpPort = httpServerInfo.getHttpUri().getPort();
assertEquals(httpServerInfo.getHttpUri(), new URI("http://[::1]:" + httpPort));
assertEquals(httpServerInfo.getHttpExternalUri(), new URI("http://[2001:db8::2:1]:" + httpPort));
int httpsPort = httpServerInfo.getHttpsUri().getPort();
assertEquals(httpServerInfo.getHttpsUri(), new URI("https://[::1]:" + httpsPort));
assertEquals(httpServerInfo.getHttpsExternalUri(), new URI("https://[2001:db8::2:1]:" + httpsPort));
int adminPort = httpServerInfo.getAdminUri().getPort();
assertEquals(httpServerInfo.getAdminUri(), new URI("https://[::1]:" + adminPort));
assertEquals(httpServerInfo.getAdminExternalUri(), new URI("https://[2001:db8::2:1]:" + adminPort));
closeChannels(httpServerInfo);
}
static void closeChannels(HttpServerInfo info)
throws IOException
{ | closeAll(info.getHttpChannel(), info.getHttpsChannel(), info.getAdminChannel()); |
chncwang/easy2db | src/test/java/com/chncwang/easy2db/DefaultEngineIntegrationTests.java | // Path: src/main/java/com/chncwang/easy2db/log/LogUtil.java
// public class LogUtil {
// private static final String FILE_NAME_A = "log4j.properties";
// private static final String FILE_NAME_B = "target/log4j.properties";
//
// public static void init() {
// final String fileName = new File(FILE_NAME_A).exists() ? FILE_NAME_A
// : FILE_NAME_B;
// PropertyConfigurator.configure(fileName);
// }
// }
| import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import com.chncwang.easy2db.log.LogUtil; | package com.chncwang.easy2db;
public class DefaultEngineIntegrationTests {
private static final Logger LOG = Logger
.getLogger(DefaultEngineIntegrationTests.class);
private DefaultEngine mEngine;
@Before
public void setUp() throws Exception { | // Path: src/main/java/com/chncwang/easy2db/log/LogUtil.java
// public class LogUtil {
// private static final String FILE_NAME_A = "log4j.properties";
// private static final String FILE_NAME_B = "target/log4j.properties";
//
// public static void init() {
// final String fileName = new File(FILE_NAME_A).exists() ? FILE_NAME_A
// : FILE_NAME_B;
// PropertyConfigurator.configure(fileName);
// }
// }
// Path: src/test/java/com/chncwang/easy2db/DefaultEngineIntegrationTests.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import com.chncwang.easy2db.log.LogUtil;
package com.chncwang.easy2db;
public class DefaultEngineIntegrationTests {
private static final Logger LOG = Logger
.getLogger(DefaultEngineIntegrationTests.class);
private DefaultEngine mEngine;
@Before
public void setUp() throws Exception { | LogUtil.init(); |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java | // Path: src/main/java/com/chncwang/easy2db/PreconditionsUtil.java
// public class PreconditionsUtil {
// private PreconditionsUtil() {}
//
// public static void checkNotNull(final Object arg, final String argName) {
// Preconditions.checkNotNull(arg, Constants.NULL_POINTER_ERROR_TEMPLATE,
// argName);
// }
// }
| import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.chncwang.easy2db.PreconditionsUtil; | package com.chncwang.easy2db.table;
public class ForeignKeyDef {
private final String mColumnName;
private final TableDef mTableDef;
public ForeignKeyDef(final String columnName, final TableDef tableDef) { | // Path: src/main/java/com/chncwang/easy2db/PreconditionsUtil.java
// public class PreconditionsUtil {
// private PreconditionsUtil() {}
//
// public static void checkNotNull(final Object arg, final String argName) {
// Preconditions.checkNotNull(arg, Constants.NULL_POINTER_ERROR_TEMPLATE,
// argName);
// }
// }
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.chncwang.easy2db.PreconditionsUtil;
package com.chncwang.easy2db.table;
public class ForeignKeyDef {
private final String mColumnName;
private final TableDef mTableDef;
public ForeignKeyDef(final String columnName, final TableDef tableDef) { | PreconditionsUtil.checkNotNull(columnName, "columnName"); |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/table/util/RowUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
| import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists; | package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
| // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
// Path: src/main/java/com/chncwang/easy2db/table/util/RowUtil.java
import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists;
package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
| public static Class<?> getPrimaryKeyType(final Row row) { |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/table/util/RowUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
| import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists; | package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
public static Class<?> getPrimaryKeyType(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getClazz();
}
public static String getPrimaryKeyName(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getName();
}
| // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
// Path: src/main/java/com/chncwang/easy2db/table/util/RowUtil.java
import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists;
package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
public static Class<?> getPrimaryKeyType(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getClazz();
}
public static String getPrimaryKeyName(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getName();
}
| public static ColumnWithValue getPrimaryKeyAsColumnWithValue(final Row row) { |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/table/util/RowUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
| import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists; | package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
public static Class<?> getPrimaryKeyType(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getClazz();
}
public static String getPrimaryKeyName(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getName();
}
public static ColumnWithValue getPrimaryKeyAsColumnWithValue(final Row row) {
return new ColumnWithValue(row.getPrimaryKeyValue().getPrimaryKeyDef()
.getColumnDef(), row.getPrimaryKeyValue().getValue());
}
public static String getUniqueKeyName(final Row row) {
return row.getUniqueKeyValue().getColumnDef().getName();
}
public static Class<?> getUniqueKeyType(final Row row) {
return row.getUniqueKeyValue().getColumnDef().getClazz();
}
public static String getColumnName(final Row row, final int index) {
return row.getColumnWithValueList().get(index).getColumnDef().getName();
}
public static List<ColumnWithValue> getForeignKeyWithValueListAsColumnWithValueList(
final Row row) { | // Path: src/main/java/com/chncwang/easy2db/table/value/ColumnWithValue.java
// public class ColumnWithValue {
// private final ColumnDef mColumnDef;
// private final Object mValue;
//
// public ColumnWithValue(final ColumnDef columnDef, final Object value) {
// mColumnDef = columnDef;
// mValue = value;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public ColumnDef getColumnDef() {
// return mColumnDef;
// }
//
// public Object getValue() {
// return mValue;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/ForeignKeyWithValue.java
// public class ForeignKeyWithValue {
// private final String mColumnName;
// private final Row mForeignRow;
//
// public ForeignKeyWithValue(final String columnName, final Row foreignRow) {
// mColumnName = columnName;
// mForeignRow = foreignRow;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public Row getForeignRow() {
// return mForeignRow;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/value/Row.java
// public class Row {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyWithValue mPrimaryKeyWithValue;
// private final ColumnWithValue mUniqueKeyWithValue;
// private final List<ForeignKeyWithValue> mForeignKeyWithValueList;
// private final List<ColumnWithValue> mColumnWithValueList;
//
// public Row(final Class<?> clazz,
// final String tableName,
// final PrimaryKeyWithValue primaryKeyValue,
// final ColumnWithValue uniqueKeyValue,
// final List<ForeignKeyWithValue> foreignKeyValues,
// final List<ColumnWithValue> columnValues) {
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyWithValue = primaryKeyValue;
// mUniqueKeyWithValue = uniqueKeyValue;
// mForeignKeyWithValueList = Collections
// .unmodifiableList(foreignKeyValues);
// mColumnWithValueList = Collections.unmodifiableList(columnValues);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyWithValue getPrimaryKeyValue() {
// return mPrimaryKeyWithValue;
// }
//
// public ColumnWithValue getUniqueKeyValue() {
// return mUniqueKeyWithValue;
// }
//
// public List<ForeignKeyWithValue> getForeignKeyWithValueList() {
// return mForeignKeyWithValueList;
// }
//
// public List<ColumnWithValue> getColumnWithValueList() {
// return mColumnWithValueList;
// }
// }
// Path: src/main/java/com/chncwang/easy2db/table/util/RowUtil.java
import java.util.List;
import com.chncwang.easy2db.table.value.ColumnWithValue;
import com.chncwang.easy2db.table.value.ForeignKeyWithValue;
import com.chncwang.easy2db.table.value.Row;
import com.google.common.collect.Lists;
package com.chncwang.easy2db.table.util;
public class RowUtil {
private RowUtil() {}
public static Class<?> getPrimaryKeyType(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getClazz();
}
public static String getPrimaryKeyName(final Row row) {
return row.getPrimaryKeyValue().getPrimaryKeyDef().getColumnDef()
.getName();
}
public static ColumnWithValue getPrimaryKeyAsColumnWithValue(final Row row) {
return new ColumnWithValue(row.getPrimaryKeyValue().getPrimaryKeyDef()
.getColumnDef(), row.getPrimaryKeyValue().getValue());
}
public static String getUniqueKeyName(final Row row) {
return row.getUniqueKeyValue().getColumnDef().getName();
}
public static Class<?> getUniqueKeyType(final Row row) {
return row.getUniqueKeyValue().getColumnDef().getClazz();
}
public static String getColumnName(final Row row, final int index) {
return row.getColumnWithValueList().get(index).getColumnDef().getName();
}
public static List<ColumnWithValue> getForeignKeyWithValueListAsColumnWithValueList(
final Row row) { | final List<ForeignKeyWithValue> foreignKeyWithValueList = row |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
| import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps; | package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
| // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
// Path: src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java
import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps;
package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
| final TableDef tableDef = tableParser.getTableDef(); |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
| import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps; | package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
| // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
// Path: src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java
import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps;
package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
| map.put(TableUtil.getPrimaryKeyName(tableDef), |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
| import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps; | package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
map.put(TableUtil.getPrimaryKeyName(tableDef),
TableUtil.getPrimaryKeyClass(tableDef));
map.put(tableDef.getUniqueKeyDef().getName(), tableDef
.getUniqueKeyDef().getClazz());
| // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
// Path: src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java
import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps;
package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
map.put(TableUtil.getPrimaryKeyName(tableDef),
TableUtil.getPrimaryKeyClass(tableDef));
map.put(tableDef.getUniqueKeyDef().getName(), tableDef
.getUniqueKeyDef().getClazz());
| for (final ForeignKeyDef foreignKeyDef : tableDef.getForeignKeyDefs()) { |
chncwang/easy2db | src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java | // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
| import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps; | package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
map.put(TableUtil.getPrimaryKeyName(tableDef),
TableUtil.getPrimaryKeyClass(tableDef));
map.put(tableDef.getUniqueKeyDef().getName(), tableDef
.getUniqueKeyDef().getClazz());
for (final ForeignKeyDef foreignKeyDef : tableDef.getForeignKeyDefs()) {
map.put(foreignKeyDef.getColumnName(),
TableUtil.getPrimaryKeyClass(foreignKeyDef.getTableDef()));
}
| // Path: src/main/java/com/chncwang/easy2db/table/ColumnDef.java
// public class ColumnDef {
// private final Class<?> mClass;
// private final String mName;
//
// public ColumnDef(final Class<?> clazz, final String name) {
// PreconditionsUtil.checkNotNull(name, "name");
//
// mClass = clazz;
// mName = name;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/ForeignKeyDef.java
// public class ForeignKeyDef {
// private final String mColumnName;
// private final TableDef mTableDef;
//
// public ForeignKeyDef(final String columnName, final TableDef tableDef) {
// PreconditionsUtil.checkNotNull(columnName, "columnName");
//
// mColumnName = columnName;
// mTableDef = tableDef;
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public String getColumnName() {
// return mColumnName;
// }
//
// public TableDef getTableDef() {
// return mTableDef;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/TableDef.java
// public class TableDef {
// private final Class<?> mClass;
// private final String mTableName;
// private final PrimaryKeyDef mPrimaryKeyDef;
// private final ColumnDef mUniqueKeyDef;
// private final List<ForeignKeyDef> mForeignKeyDefs;
// private final List<ColumnDef> mColumnDefs;
//
// public TableDef(final Class<?> clazz, final String tableName,
// final PrimaryKeyDef primaryKeyDef,
// final ColumnDef uniqueKeyDef,
// final List<ForeignKeyDef> foreignKeyDefs,
// final List<ColumnDef> columnDefs) {
// PreconditionsUtil.checkNotNull(tableName, "tableName");
// PreconditionsUtil.checkNotNull(primaryKeyDef, "primaryKeyDef");
// PreconditionsUtil.checkNotNull(uniqueKeyDef, "uniqueKeyDef");
//
// mClass = clazz;
// mTableName = tableName;
// mPrimaryKeyDef = primaryKeyDef;
// mUniqueKeyDef = uniqueKeyDef;
// mForeignKeyDefs = Collections.unmodifiableList(foreignKeyDefs);
// mColumnDefs = Collections.unmodifiableList(columnDefs);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this,
// ToStringStyle.MULTI_LINE_STYLE);
// }
//
// public Class<?> getClazz() {
// return mClass;
// }
//
// public String getTableName() {
// return mTableName;
// }
//
// public PrimaryKeyDef getPrimaryKeyDef() {
// return mPrimaryKeyDef;
// }
//
// public ColumnDef getUniqueKeyDef() {
// return mUniqueKeyDef;
// }
//
// public List<ForeignKeyDef> getForeignKeyDefs() {
// return mForeignKeyDefs;
// }
//
// public List<ColumnDef> getColumnDefs() {
// return mColumnDefs;
// }
// }
//
// Path: src/main/java/com/chncwang/easy2db/table/util/TableUtil.java
// public class TableUtil {
// private TableUtil() {}
//
// public static String getPrimaryKeyName(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getName();
// }
//
// public static Class<?> getPrimaryKeyClass(final TableDef tableDef) {
// return tableDef.getPrimaryKeyDef().getColumnDef().getClazz();
// }
// }
// Path: src/main/java/com/chncwang/easy2db/parser/TableParserUtil.java
import java.util.Map;
import com.chncwang.easy2db.table.ColumnDef;
import com.chncwang.easy2db.table.ForeignKeyDef;
import com.chncwang.easy2db.table.TableDef;
import com.chncwang.easy2db.table.util.TableUtil;
import com.google.common.collect.Maps;
package com.chncwang.easy2db.parser;
public class TableParserUtil {
private TableParserUtil() {}
public static Map<String, Class<?>> createColumnClassMap(
final TableParser tableParser) {
final Map<String, Class<?>> map = Maps.newTreeMap();
final TableDef tableDef = tableParser.getTableDef();
map.put(TableUtil.getPrimaryKeyName(tableDef),
TableUtil.getPrimaryKeyClass(tableDef));
map.put(tableDef.getUniqueKeyDef().getName(), tableDef
.getUniqueKeyDef().getClazz());
for (final ForeignKeyDef foreignKeyDef : tableDef.getForeignKeyDefs()) {
map.put(foreignKeyDef.getColumnName(),
TableUtil.getPrimaryKeyClass(foreignKeyDef.getTableDef()));
}
| for (final ColumnDef columnDef : tableDef.getColumnDefs()) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.