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 |
|---|---|---|---|---|---|---|
jmhertlein/MCTowns | src/test/java/cafe/josh/mctowns/util/test/MCTConfigTest.java | // Path: src/main/java/cafe/josh/mctowns/util/MCTConfig.java
// public enum MCTConfig {
// WG_VER_REGEX("wgRequirement", ".*"),
// DEFAULT_TOWN("defaultTown", null),
// ECONOMY_ENABLED("economyEnabled", false),
// MAYORS_CAN_BUY_TERRITORIES("mayorsCanBuyTerritories", false),
// PRICE_PER_XZ_BLOCK("pricePerXZBlock", 0),
// MIN_NUM_PLAYERS_TO_BUY_TERRITORY("minNumPlayersToBuyTerritory", 3),
// ALLOW_TOWN_FRIENDLY_FIRE_MANAGEMENT("allowTownFriendlyFireManagement", true),
// QUICKSELECT_TOOL("quickSelectTool", "WOOD_HOE"),
// LOG_COMMANDS("logCommands", true),
// PLAYERS_CAN_JOIN_MULTIPLE_TOWNS("playersCanJoinMultipleTowns", false),
// TERRITORY_XZ_SIZE_LIMIT("territoryXZSizeLimit", 800),
// DEBUG_MODE_ENABLED("debugModeEnabled", false),
// CURRENCY_INPUT_PATTERN("currencyInputPattern", "^\\d{1,10}(\\.\\d{1,10})?$");
//
// private static final MCTownsPlugin p = MCTownsPlugin.getPlugin();
//
// private final Object dflt;
// private final String key;
//
// private MCTConfig(String key, Object dflt) {
// this.dflt = dflt;
// this.key = key;
// }
//
// public void set(Object value) {
// MCTownsPlugin.getPlugin().getConfig().set(getKey(), value);
// }
//
// public Object getObject() {
// return p == null ? dflt : p.getConfig().get(this.getKey(), dflt);
// }
//
// public int getInt() {
// return p == null ? (int) dflt : p.getConfig().getInt(this.getKey(), (int) dflt);
// }
//
// public String getString() {
// String defString = dflt == null ? null : dflt.toString();
// return p == null ? defString : p.getConfig().getString(this.getKey(), defString);
// }
//
// public boolean getBoolean() {
// return p == null ? (boolean) dflt : p.getConfig().getBoolean(this.getKey(), (boolean) dflt);
// }
//
// public String getKey() {
// return key;
// }
// }
| import org.junit.Test;
import cafe.josh.mctowns.util.MCTConfig; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cafe.josh.mctowns.util.test;
/**
*
* @author joshua
*/
public class MCTConfigTest {
@Test
public void testBukkitlessQuery() { | // Path: src/main/java/cafe/josh/mctowns/util/MCTConfig.java
// public enum MCTConfig {
// WG_VER_REGEX("wgRequirement", ".*"),
// DEFAULT_TOWN("defaultTown", null),
// ECONOMY_ENABLED("economyEnabled", false),
// MAYORS_CAN_BUY_TERRITORIES("mayorsCanBuyTerritories", false),
// PRICE_PER_XZ_BLOCK("pricePerXZBlock", 0),
// MIN_NUM_PLAYERS_TO_BUY_TERRITORY("minNumPlayersToBuyTerritory", 3),
// ALLOW_TOWN_FRIENDLY_FIRE_MANAGEMENT("allowTownFriendlyFireManagement", true),
// QUICKSELECT_TOOL("quickSelectTool", "WOOD_HOE"),
// LOG_COMMANDS("logCommands", true),
// PLAYERS_CAN_JOIN_MULTIPLE_TOWNS("playersCanJoinMultipleTowns", false),
// TERRITORY_XZ_SIZE_LIMIT("territoryXZSizeLimit", 800),
// DEBUG_MODE_ENABLED("debugModeEnabled", false),
// CURRENCY_INPUT_PATTERN("currencyInputPattern", "^\\d{1,10}(\\.\\d{1,10})?$");
//
// private static final MCTownsPlugin p = MCTownsPlugin.getPlugin();
//
// private final Object dflt;
// private final String key;
//
// private MCTConfig(String key, Object dflt) {
// this.dflt = dflt;
// this.key = key;
// }
//
// public void set(Object value) {
// MCTownsPlugin.getPlugin().getConfig().set(getKey(), value);
// }
//
// public Object getObject() {
// return p == null ? dflt : p.getConfig().get(this.getKey(), dflt);
// }
//
// public int getInt() {
// return p == null ? (int) dflt : p.getConfig().getInt(this.getKey(), (int) dflt);
// }
//
// public String getString() {
// String defString = dflt == null ? null : dflt.toString();
// return p == null ? defString : p.getConfig().getString(this.getKey(), defString);
// }
//
// public boolean getBoolean() {
// return p == null ? (boolean) dflt : p.getConfig().getBoolean(this.getKey(), (boolean) dflt);
// }
//
// public String getKey() {
// return key;
// }
// }
// Path: src/test/java/cafe/josh/mctowns/util/test/MCTConfigTest.java
import org.junit.Test;
import cafe.josh.mctowns.util.MCTConfig;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cafe.josh.mctowns.util.test;
/**
*
* @author joshua
*/
public class MCTConfigTest {
@Test
public void testBukkitlessQuery() { | MCTConfig.DEBUG_MODE_ENABLED.getBoolean(); |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/ui/activity/Password.java | // Path: gasst/src/main/java/com/duanze/gasst/ui/activity/base/BaseActivity.java
// public class BaseActivity extends AppCompatActivity {
// private LinearLayout rootLayout;
//
// private static boolean first = true;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// initTheme();
// super.onCreate(savedInstanceState);
// // 这句很关键,注意是调用父类的方法
// super.setContentView(R.layout.activity_base);
// // 经测试在代码里直接声明透明状态栏更有效
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
// localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
//
// // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//
// //沉浸式时,对状态栏染色
// // create our manager instance after the content view is set
// SystemBarTintManager tintManager = new SystemBarTintManager(this);
// tintManager.setStatusBarTintColor(getStatusBarColor());
// // enable status bar tint
// tintManager.setStatusBarTintEnabled(true);
// // // enable navigation bar tint
// // tintManager.setNavigationBarTintEnabled(true);
// }
//
// initToolbar();
// }
//
// private void initTheme() {
// if (first) {
// MyLitePrefs.initFromXml(this);
// first=false;
// }
// ThemeUtils.Theme theme = MyLitePrefs.getTheme();
// ThemeUtils.changTheme(this, theme);
// }
//
// public int getStatusBarColor() {
// return getColorPrimaryDark();
// }
//
// public int getColorPrimaryDark() {
// TypedValue typedValue = new TypedValue();
// getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
// return typedValue.data;
// }
//
// public int getColorPrimary() {
// TypedValue typedValue = new TypedValue();
// getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
// return typedValue.data;
// }
//
// private void initToolbar() {
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// if (toolbar != null) {
// setSupportActionBar(toolbar);
// }
// }
//
// public LinearLayout getRootLayout() {
// return rootLayout;
// }
//
// @Override
// public void setContentView(int layoutId) {
// setContentView(View.inflate(this, layoutId, null));
// }
//
// @Override
// public void setContentView(View view) {
// rootLayout = (LinearLayout) findViewById(R.id.root_layout);
// if (rootLayout == null) return;
// rootLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// initToolbar();
// }
//
// }
//
// Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
| import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.duanze.gasst.R;
import com.duanze.gasst.ui.activity.base.BaseActivity;
import com.duanze.gasst.util.liteprefs.MyLitePrefs; | package com.duanze.gasst.ui.activity;
/**
* Created by duanze on 2015/7/11.
*/
public class Password extends BaseActivity {
public static final int REQUEST_VALIDATE_PWD = 233;
private String password;
public static void actionStart(Context context, String hint, String password) {
Intent intent = new Intent(context, Password.class); | // Path: gasst/src/main/java/com/duanze/gasst/ui/activity/base/BaseActivity.java
// public class BaseActivity extends AppCompatActivity {
// private LinearLayout rootLayout;
//
// private static boolean first = true;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// initTheme();
// super.onCreate(savedInstanceState);
// // 这句很关键,注意是调用父类的方法
// super.setContentView(R.layout.activity_base);
// // 经测试在代码里直接声明透明状态栏更有效
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
// localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
//
// // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//
// //沉浸式时,对状态栏染色
// // create our manager instance after the content view is set
// SystemBarTintManager tintManager = new SystemBarTintManager(this);
// tintManager.setStatusBarTintColor(getStatusBarColor());
// // enable status bar tint
// tintManager.setStatusBarTintEnabled(true);
// // // enable navigation bar tint
// // tintManager.setNavigationBarTintEnabled(true);
// }
//
// initToolbar();
// }
//
// private void initTheme() {
// if (first) {
// MyLitePrefs.initFromXml(this);
// first=false;
// }
// ThemeUtils.Theme theme = MyLitePrefs.getTheme();
// ThemeUtils.changTheme(this, theme);
// }
//
// public int getStatusBarColor() {
// return getColorPrimaryDark();
// }
//
// public int getColorPrimaryDark() {
// TypedValue typedValue = new TypedValue();
// getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);
// return typedValue.data;
// }
//
// public int getColorPrimary() {
// TypedValue typedValue = new TypedValue();
// getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
// return typedValue.data;
// }
//
// private void initToolbar() {
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// if (toolbar != null) {
// setSupportActionBar(toolbar);
// }
// }
//
// public LinearLayout getRootLayout() {
// return rootLayout;
// }
//
// @Override
// public void setContentView(int layoutId) {
// setContentView(View.inflate(this, layoutId, null));
// }
//
// @Override
// public void setContentView(View view) {
// rootLayout = (LinearLayout) findViewById(R.id.root_layout);
// if (rootLayout == null) return;
// rootLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
// initToolbar();
// }
//
// }
//
// Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
// Path: gasst/src/main/java/com/duanze/gasst/ui/activity/Password.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.duanze.gasst.R;
import com.duanze.gasst.ui.activity.base.BaseActivity;
import com.duanze.gasst.util.liteprefs.MyLitePrefs;
package com.duanze.gasst.ui.activity;
/**
* Created by duanze on 2015/7/11.
*/
public class Password extends BaseActivity {
public static final int REQUEST_VALIDATE_PWD = 233;
private String password;
public static void actionStart(Context context, String hint, String password) {
Intent intent = new Intent(context, Password.class); | intent.putExtra(MyLitePrefs.PASSWORD_HINT, hint); |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/data/model/GNoteDB.java | // Path: gasst/src/main/java/com/duanze/gasst/data/db/GNoteOpenHelper.java
// public class GNoteOpenHelper extends SQLiteOpenHelper {
//
// /**
// * GNote建表语句
// */
// public static final String CREATE_TABLE =
// "create table table_gnote ("
// + "id integer primary key autoincrement,"
// + "time text,"
// + "alert_time text,"
// + "is_passed integer,"
// + "content text,"
// + "done integer,"
// + "color integer,"
// + "edit_time integer,"
// + "created_time integer,"
// + "syn_status integer,"
// + "guid text,"
// + "book_guid text,"
// + "deleted integer,"
// + "gnotebook_id integer"
// + ")";
//
// public static final String CREATE_TABLE_NOTEBOOK =
// "create table " + GNoteDB.TABLE_NOTEBOOK + " ("
// + "id integer primary key autoincrement,"
// + "name text,"
// + "syn_status integer,"
// + "notebook_guid text,"
// + "deleted integer,"
// + "num integer,"
// + "selected integer"
// + ")";
//
// public GNoteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
// int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(CREATE_TABLE);
// db.execSQL(CREATE_TABLE_NOTEBOOK);
// }
//
// /**
// * 升级数据库
// *
// * @param db
// * @param oldVersion
// * @param newVersion
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL("alter table table_gnote add column gnotebook_id integer");
// db.execSQL(CREATE_TABLE_NOTEBOOK);
// default:
// }
// }
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.duanze.gasst.data.db.GNoteOpenHelper;
import java.util.ArrayList;
import java.util.List; | package com.duanze.gasst.data.model;
public class GNoteDB {
public static final String TAG = "GNoteDB";
/**
* 数据库名
*/
public static final String DB_NAME = "db_gnote";
public static final String TABLE_NAME = "table_gnote";
public static final String TABLE_NOTEBOOK = "table_gnotebook";
// common
public static final String ID = "id";
public static final String SYN_STATUS = "syn_status";
public static final String DELETED = "deleted";
// table_gnote
public static final String TIME = "time";
public static final String ALERT_TIME = "alert_time";
public static final String IS_PASSED = "is_passed";
public static final String CONTENT = "content";
public static final String IS_DONE = "done";
public static final String COLOR = "color";
public static final String EDIT_TIME = "edit_time";
public static final String CREATED_TIME = "created_time";
public static final String GUID = "guid";
public static final String BOOK_GUID = "book_guid";
public static final String GNOTEBOOK_ID = "gnotebook_id";
// table_gnotebook
public static final String NAME = "name";
public static final String NOTEBOOK_GUID = "notebook_guid";
public static final String NOTES_NUM = "num";
public static final String SELECTED = "selected";
/**
* 数据库版本
*/
public static final int VERSION = 2;
private static GNoteDB gNoteDB;
private SQLiteDatabase db;
private GNoteDB(Context context) { | // Path: gasst/src/main/java/com/duanze/gasst/data/db/GNoteOpenHelper.java
// public class GNoteOpenHelper extends SQLiteOpenHelper {
//
// /**
// * GNote建表语句
// */
// public static final String CREATE_TABLE =
// "create table table_gnote ("
// + "id integer primary key autoincrement,"
// + "time text,"
// + "alert_time text,"
// + "is_passed integer,"
// + "content text,"
// + "done integer,"
// + "color integer,"
// + "edit_time integer,"
// + "created_time integer,"
// + "syn_status integer,"
// + "guid text,"
// + "book_guid text,"
// + "deleted integer,"
// + "gnotebook_id integer"
// + ")";
//
// public static final String CREATE_TABLE_NOTEBOOK =
// "create table " + GNoteDB.TABLE_NOTEBOOK + " ("
// + "id integer primary key autoincrement,"
// + "name text,"
// + "syn_status integer,"
// + "notebook_guid text,"
// + "deleted integer,"
// + "num integer,"
// + "selected integer"
// + ")";
//
// public GNoteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
// int version) {
// super(context, name, factory, version);
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(CREATE_TABLE);
// db.execSQL(CREATE_TABLE_NOTEBOOK);
// }
//
// /**
// * 升级数据库
// *
// * @param db
// * @param oldVersion
// * @param newVersion
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL("alter table table_gnote add column gnotebook_id integer");
// db.execSQL(CREATE_TABLE_NOTEBOOK);
// default:
// }
// }
// }
// Path: gasst/src/main/java/com/duanze/gasst/data/model/GNoteDB.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.duanze.gasst.data.db.GNoteOpenHelper;
import java.util.ArrayList;
import java.util.List;
package com.duanze.gasst.data.model;
public class GNoteDB {
public static final String TAG = "GNoteDB";
/**
* 数据库名
*/
public static final String DB_NAME = "db_gnote";
public static final String TABLE_NAME = "table_gnote";
public static final String TABLE_NOTEBOOK = "table_gnotebook";
// common
public static final String ID = "id";
public static final String SYN_STATUS = "syn_status";
public static final String DELETED = "deleted";
// table_gnote
public static final String TIME = "time";
public static final String ALERT_TIME = "alert_time";
public static final String IS_PASSED = "is_passed";
public static final String CONTENT = "content";
public static final String IS_DONE = "done";
public static final String COLOR = "color";
public static final String EDIT_TIME = "edit_time";
public static final String CREATED_TIME = "created_time";
public static final String GUID = "guid";
public static final String BOOK_GUID = "book_guid";
public static final String GNOTEBOOK_ID = "gnotebook_id";
// table_gnotebook
public static final String NAME = "name";
public static final String NOTEBOOK_GUID = "notebook_guid";
public static final String NOTES_NUM = "num";
public static final String SELECTED = "selected";
/**
* 数据库版本
*/
public static final int VERSION = 2;
private static GNoteDB gNoteDB;
private SQLiteDatabase db;
private GNoteDB(Context context) { | GNoteOpenHelper openHelper = new GNoteOpenHelper(context, DB_NAME, null, VERSION); |
duanze/PureNote | LitePreferences/src/main/java/com/duanze/litepreferences/ActualUtil.java | // Path: LitePreferences/src/main/java/com/duanze/litepreferences/model/Pref.java
// public class Pref {
//
// public String key;
//
// /**
// * use String store the default value
// */
// public String defValue;
//
// /**
// * use String store the current value
// */
// public String curValue;
//
// /**
// * flag to show the pref has queried its data from SharedPreferences or not
// */
// public boolean queried = false;
//
// public Pref() {
// }
//
// public Pref(String key, String defValue) {
// this.key = key;
// this.defValue = defValue;
// }
//
// public Pref(String key, int defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, long defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, float defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, boolean defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public int getDefInt() {
// return Integer.parseInt(defValue);
// }
//
// public long getDefLong() {
// return Long.parseLong(defValue);
// }
//
// public float getDefFloat() {
// return Float.parseFloat(defValue);
// }
//
// public boolean getDefBoolean() {
// return Boolean.parseBoolean(defValue);
// }
//
// public String getDefString() {
// return defValue;
// }
//
// public int getCurInt() {
// return Integer.parseInt(curValue);
// }
//
// public long getCurLong() {
// return Long.parseLong(curValue);
// }
//
// public float getCurFloat() {
// return Float.parseFloat(curValue);
// }
//
// public boolean getCurBoolean() {
// return Boolean.parseBoolean(curValue);
// }
//
// public String getCurString() {
// return curValue;
// }
//
// public void setValue(int value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(long value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(float value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(boolean value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(String value) {
// curValue = value;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.duanze.litepreferences.model.Pref;
import java.util.Map;
import java.util.Set; | /*
* Copyright 2015 Duanze
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.duanze.litepreferences;
/**
* Created by Duanze on 15-11-19.
*/
public class ActualUtil {
private String name;
private SharedPreferences mSharedPreferences; | // Path: LitePreferences/src/main/java/com/duanze/litepreferences/model/Pref.java
// public class Pref {
//
// public String key;
//
// /**
// * use String store the default value
// */
// public String defValue;
//
// /**
// * use String store the current value
// */
// public String curValue;
//
// /**
// * flag to show the pref has queried its data from SharedPreferences or not
// */
// public boolean queried = false;
//
// public Pref() {
// }
//
// public Pref(String key, String defValue) {
// this.key = key;
// this.defValue = defValue;
// }
//
// public Pref(String key, int defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, long defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, float defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, boolean defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public int getDefInt() {
// return Integer.parseInt(defValue);
// }
//
// public long getDefLong() {
// return Long.parseLong(defValue);
// }
//
// public float getDefFloat() {
// return Float.parseFloat(defValue);
// }
//
// public boolean getDefBoolean() {
// return Boolean.parseBoolean(defValue);
// }
//
// public String getDefString() {
// return defValue;
// }
//
// public int getCurInt() {
// return Integer.parseInt(curValue);
// }
//
// public long getCurLong() {
// return Long.parseLong(curValue);
// }
//
// public float getCurFloat() {
// return Float.parseFloat(curValue);
// }
//
// public boolean getCurBoolean() {
// return Boolean.parseBoolean(curValue);
// }
//
// public String getCurString() {
// return curValue;
// }
//
// public void setValue(int value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(long value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(float value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(boolean value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(String value) {
// curValue = value;
// }
// }
// Path: LitePreferences/src/main/java/com/duanze/litepreferences/ActualUtil.java
import android.content.Context;
import android.content.SharedPreferences;
import com.duanze.litepreferences.model.Pref;
import java.util.Map;
import java.util.Set;
/*
* Copyright 2015 Duanze
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.duanze.litepreferences;
/**
* Created by Duanze on 15-11-19.
*/
public class ActualUtil {
private String name;
private SharedPreferences mSharedPreferences; | private Map<String, Pref> mMap; |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/ui/view/MinusTextView.java | // Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
| import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.widget.TextView;
import com.duanze.gasst.util.liteprefs.MyLitePrefs; | package com.duanze.gasst.ui.view;
public class MinusTextView extends TextView {
public static final String TAG = MinusTextView.class.getSimpleName();
private static int width;
private static int height;
private static final float GOLDEN_PROPORTION = (float) 0.618;
private static final float ACTUAL_PROPORTION = (float) 0.418;
{
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
width = point.x;
height = point.y;
}
public MinusTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = getMeasuredWidth();
int heightSize = getMeasuredHeight();
// if (heightSize > height * ACTUAL_PROPORTION) {
// heightSize = (int) (height * ACTUAL_PROPORTION);
// }
| // Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
// Path: gasst/src/main/java/com/duanze/gasst/ui/view/MinusTextView.java
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.widget.TextView;
import com.duanze.gasst.util.liteprefs.MyLitePrefs;
package com.duanze.gasst.ui.view;
public class MinusTextView extends TextView {
public static final String TAG = MinusTextView.class.getSimpleName();
private static int width;
private static int height;
private static final float GOLDEN_PROPORTION = (float) 0.618;
private static final float ACTUAL_PROPORTION = (float) 0.418;
{
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
width = point.x;
height = point.y;
}
public MinusTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = getMeasuredWidth();
int heightSize = getMeasuredHeight();
// if (heightSize > height * ACTUAL_PROPORTION) {
// heightSize = (int) (height * ACTUAL_PROPORTION);
// }
| float ratio = MyLitePrefs.getFloat(MyLitePrefs.NOTE_MAX_LENGTH_RATIO); |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/util/ThemeUtils.java | // Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
| import android.app.Activity;
import android.content.Context;
import com.duanze.gasst.R;
import com.duanze.gasst.util.liteprefs.MyLitePrefs; | style = R.style.YellowTheme;
break;
case BLUE:
style = R.style.BlueTheme;
break;
case PINK:
style = R.style.PinkTheme;
break;
case GREEN:
style = R.style.GreenTheme;
break;
case DEEP_PURPLE:
style = R.style.DeepPurpleTheme;
break;
case GRAY:
style = R.style.GrayTheme;
break;
case LIGHT_PINK:
style = R.style.LightPinkTheme;
break;
case BROWN:
style = R.style.BrownTheme;
break;
default:
break;
}
activity.setTheme(style);
}
public static Theme getCurrentTheme(Context context) { | // Path: gasst/src/main/java/com/duanze/gasst/util/liteprefs/MyLitePrefs.java
// public class MyLitePrefs extends BaseLitePrefs {
//
// public static final String DATA = "gasst_pref";
//
// public static final String THEME = "choose_theme_key";
// public static final String CONCENTRATE_WRITE = "concentrate_write_key";
// public static final String ONE_COLUMN = "one_column_key";
// public static final String CREATE_ORDER = "create_order_key";
// public static final String NOTE_MAX_LENGTH_RATIO = "note_max_length_key";
//
// public static final String PASSWORD_GUARD = "password_guard";
// public static final String SHOW_UNIVERSAL_SWITCH = "show_universal_switch";
// public static final String USE_UNIVERSAL_PASSWORD = "use_universal_password";
// public static final String UNIVERSAL_PASSWORD = "-_-#";
// public static final String PASSWORD = "password";
// public static final String PASSWORD_HINT = "password_hint";
//
// public static final String NOTIFICATION_ALWAYS_SHOW = "notification_always_show_key";
//
// public static final String LIGHTNING_EXTRACT = "lightning_extract";
// public static final String LIGHTNING_EXTRACT_SAVE_LOCATION = "lightning_extract_save_location";
// public static final String QUICK_WRITE_SAVE_LOCATION = "quick_write_save_location";
//
// public static final String GNOTEBOOK_ID = "gnotebook_id";
// public static final String PURENOTE_NOTE_NUM = "purenote_note_num";
//
// public static void initFromXml(Context context) {
// try {
// initFromXml(context, R.xml.prefs);
// } catch (IOException | XmlPullParserException e) {
// e.printStackTrace();
// }
// }
//
// public static ThemeUtils.Theme getTheme() {
// return ThemeUtils.Theme.mapValueToTheme(getInt(THEME));
// }
//
// public static boolean setTheme(int value) {
// return putInt(THEME, value);
// }
//
// }
// Path: gasst/src/main/java/com/duanze/gasst/util/ThemeUtils.java
import android.app.Activity;
import android.content.Context;
import com.duanze.gasst.R;
import com.duanze.gasst.util.liteprefs.MyLitePrefs;
style = R.style.YellowTheme;
break;
case BLUE:
style = R.style.BlueTheme;
break;
case PINK:
style = R.style.PinkTheme;
break;
case GREEN:
style = R.style.GreenTheme;
break;
case DEEP_PURPLE:
style = R.style.DeepPurpleTheme;
break;
case GRAY:
style = R.style.GrayTheme;
break;
case LIGHT_PINK:
style = R.style.LightPinkTheme;
break;
case BROWN:
style = R.style.BrownTheme;
break;
default:
break;
}
activity.setTheme(style);
}
public static Theme getCurrentTheme(Context context) { | return MyLitePrefs.getTheme(); |
duanze/PureNote | LitePreferences/src/main/java/com/duanze/litepreferences/LiteInterface.java | // Path: LitePreferences/src/main/java/com/duanze/litepreferences/model/Pref.java
// public class Pref {
//
// public String key;
//
// /**
// * use String store the default value
// */
// public String defValue;
//
// /**
// * use String store the current value
// */
// public String curValue;
//
// /**
// * flag to show the pref has queried its data from SharedPreferences or not
// */
// public boolean queried = false;
//
// public Pref() {
// }
//
// public Pref(String key, String defValue) {
// this.key = key;
// this.defValue = defValue;
// }
//
// public Pref(String key, int defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, long defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, float defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, boolean defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public int getDefInt() {
// return Integer.parseInt(defValue);
// }
//
// public long getDefLong() {
// return Long.parseLong(defValue);
// }
//
// public float getDefFloat() {
// return Float.parseFloat(defValue);
// }
//
// public boolean getDefBoolean() {
// return Boolean.parseBoolean(defValue);
// }
//
// public String getDefString() {
// return defValue;
// }
//
// public int getCurInt() {
// return Integer.parseInt(curValue);
// }
//
// public long getCurLong() {
// return Long.parseLong(curValue);
// }
//
// public float getCurFloat() {
// return Float.parseFloat(curValue);
// }
//
// public boolean getCurBoolean() {
// return Boolean.parseBoolean(curValue);
// }
//
// public String getCurString() {
// return curValue;
// }
//
// public void setValue(int value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(long value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(float value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(boolean value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(String value) {
// curValue = value;
// }
// }
| import android.content.Context;
import com.duanze.litepreferences.model.Pref;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Map; | package com.duanze.litepreferences;
/**
* Created by Duanze on 15-11-22.
*/
public interface LiteInterface {
LiteInterface getImpl();
void initFromXmlLite(Context context, int res) throws IOException, XmlPullParserException;
| // Path: LitePreferences/src/main/java/com/duanze/litepreferences/model/Pref.java
// public class Pref {
//
// public String key;
//
// /**
// * use String store the default value
// */
// public String defValue;
//
// /**
// * use String store the current value
// */
// public String curValue;
//
// /**
// * flag to show the pref has queried its data from SharedPreferences or not
// */
// public boolean queried = false;
//
// public Pref() {
// }
//
// public Pref(String key, String defValue) {
// this.key = key;
// this.defValue = defValue;
// }
//
// public Pref(String key, int defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, long defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, float defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public Pref(String key, boolean defValue) {
// this.key = key;
// this.defValue = String.valueOf(defValue);
// }
//
// public int getDefInt() {
// return Integer.parseInt(defValue);
// }
//
// public long getDefLong() {
// return Long.parseLong(defValue);
// }
//
// public float getDefFloat() {
// return Float.parseFloat(defValue);
// }
//
// public boolean getDefBoolean() {
// return Boolean.parseBoolean(defValue);
// }
//
// public String getDefString() {
// return defValue;
// }
//
// public int getCurInt() {
// return Integer.parseInt(curValue);
// }
//
// public long getCurLong() {
// return Long.parseLong(curValue);
// }
//
// public float getCurFloat() {
// return Float.parseFloat(curValue);
// }
//
// public boolean getCurBoolean() {
// return Boolean.parseBoolean(curValue);
// }
//
// public String getCurString() {
// return curValue;
// }
//
// public void setValue(int value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(long value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(float value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(boolean value) {
// curValue = String.valueOf(value);
// }
//
// public void setValue(String value) {
// curValue = value;
// }
// }
// Path: LitePreferences/src/main/java/com/duanze/litepreferences/LiteInterface.java
import android.content.Context;
import com.duanze.litepreferences.model.Pref;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.Map;
package com.duanze.litepreferences;
/**
* Created by Duanze on 15-11-22.
*/
public interface LiteInterface {
LiteInterface getImpl();
void initFromXmlLite(Context context, int res) throws IOException, XmlPullParserException;
| void initFromMapLite(Context context, String name, Map<String, Pref> map); |
duanze/PureNote | gasst/src/main/java/com/duanze/gasst/MyApplication.java | // Path: gasst/src/main/java/com/duanze/gasst/ui/activity/StartActivity.java
// public class SyncHandler extends Handler {
// @Override
// public void handleMessage(Message msg) {
// super.handleMessage(msg);
// switch (msg.what) {
// case Evernote.SYNC_START:
// setRefreshing(true);
// break;
// case Evernote.SYNC_END:
// setRefreshing(false);
// break;
// case UPGRADE_START:
// showDialog(OPERATE);
// break;
// case UPGRADE_END:
// dismissDialog(OPERATE);
// break;
//
// case NEED_RECREATE:
// recreate();
// break;
// case NEED_CONFIG_LAYOUT:
// gNoteRecyclerView.configLayoutManager();
// break;
// case NEED_NOTIFY:
// gNoteRecyclerView.notifyDataSetChanged();
// break;
// default:
// break;
// }
// }
// }
| import android.app.Application;
import android.content.Context;
import com.duanze.gasst.ui.activity.StartActivity.SyncHandler; | package com.duanze.gasst;
public class MyApplication extends Application {
private static Context mContext; | // Path: gasst/src/main/java/com/duanze/gasst/ui/activity/StartActivity.java
// public class SyncHandler extends Handler {
// @Override
// public void handleMessage(Message msg) {
// super.handleMessage(msg);
// switch (msg.what) {
// case Evernote.SYNC_START:
// setRefreshing(true);
// break;
// case Evernote.SYNC_END:
// setRefreshing(false);
// break;
// case UPGRADE_START:
// showDialog(OPERATE);
// break;
// case UPGRADE_END:
// dismissDialog(OPERATE);
// break;
//
// case NEED_RECREATE:
// recreate();
// break;
// case NEED_CONFIG_LAYOUT:
// gNoteRecyclerView.configLayoutManager();
// break;
// case NEED_NOTIFY:
// gNoteRecyclerView.notifyDataSetChanged();
// break;
// default:
// break;
// }
// }
// }
// Path: gasst/src/main/java/com/duanze/gasst/MyApplication.java
import android.app.Application;
import android.content.Context;
import com.duanze.gasst.ui.activity.StartActivity.SyncHandler;
package com.duanze.gasst;
public class MyApplication extends Application {
private static Context mContext; | private SyncHandler mHandler; |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/sharingdevice/mySharedFragment.java | // Path: src/com/gizwits/opensource/appkit/CommonModule/GosConstant.java
// public class GosConstant {
//
// public static List<ScanResult> ssidList = new ArrayList<ScanResult>();
//
// public static int nowPager = -1;
//
// public static List<GizUserInfo> mybindUsers = new ArrayList<GizUserInfo>();
//
// public static List<GizDeviceSharingInfo> mydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static List<GizDeviceSharingInfo> newmydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static boolean isEdit = false;
//
// public static String mozu = "https://item.taobao.com/item.htm?spm=686.1000925.0.0.nPcYfD&id=542479181481";
//
// // 设备热点默认密码
// public static final String SoftAP_PSW = "123456789";
//
//
// // 设备热点默认前缀
// public static final String SoftAP_Start = "XPG-GAgent";
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosConstant;
import android.content.Intent;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView; | initData();
myadapter1 = new myadapter();
mListView.setAdapter(myadapter1);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
GizWifiDevice wifiDevice = list.get(arg2);
GizDeviceSharingUserRole sharingRole = wifiDevice.getSharingRole();
int role = sharingRole.ordinal();
boolean isgetsharing = false;
if (role == 2) {
isgetsharing = true;
}
mListView.setEnabled(false);
mListView.postDelayed(new Runnable() {
@Override
public void run() {
mListView.setEnabled(true);
}
}, 1000);
Intent tent = new Intent(getActivity(), SharedDeviceManagerActivity.class);
| // Path: src/com/gizwits/opensource/appkit/CommonModule/GosConstant.java
// public class GosConstant {
//
// public static List<ScanResult> ssidList = new ArrayList<ScanResult>();
//
// public static int nowPager = -1;
//
// public static List<GizUserInfo> mybindUsers = new ArrayList<GizUserInfo>();
//
// public static List<GizDeviceSharingInfo> mydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static List<GizDeviceSharingInfo> newmydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static boolean isEdit = false;
//
// public static String mozu = "https://item.taobao.com/item.htm?spm=686.1000925.0.0.nPcYfD&id=542479181481";
//
// // 设备热点默认密码
// public static final String SoftAP_PSW = "123456789";
//
//
// // 设备热点默认前缀
// public static final String SoftAP_Start = "XPG-GAgent";
//
// }
// Path: src/com/gizwits/opensource/appkit/sharingdevice/mySharedFragment.java
import java.util.ArrayList;
import java.util.List;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosConstant;
import android.content.Intent;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
initData();
myadapter1 = new myadapter();
mListView.setAdapter(myadapter1);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
GizWifiDevice wifiDevice = list.get(arg2);
GizDeviceSharingUserRole sharingRole = wifiDevice.getSharingRole();
int role = sharingRole.ordinal();
boolean isgetsharing = false;
if (role == 2) {
isgetsharing = true;
}
mListView.setEnabled(false);
mListView.postDelayed(new Runnable() {
@Override
public void run() {
mListView.setEnabled(true);
}
}, 1000);
Intent tent = new Intent(getActivity(), SharedDeviceManagerActivity.class);
| GosConstant.mybindUsers.clear(); |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/CommonModule/GosBaseActivity.java | // Path: src/com/gizwits/opensource/appkit/MessageCenter.java
// public class MessageCenter {
// private static MessageCenter mCenter;
// int flag = 0;
//
// GosDeploy gosDeploy;
//
// private int SETCLOUD = 1111;
//
// private MessageCenter(Context c) {
// if (mCenter == null) {
// init(c);
// }
// }
//
// private void init(Context c) {
// gosDeploy = new GosDeploy(c);
// String AppID = GosDeploy.setAppID();
// String AppSecret = GosDeploy.setAppSecret();
// if (TextUtils.isEmpty(AppID) || AppID.contains("your_app_id") || TextUtils.isEmpty(AppSecret)
// || AppSecret.contains("your_app_secret")) {
// String AppID_Toast = c.getString(R.string.AppID_Toast);
// if (flag == 0) {
// Toast.makeText(c, AppID_Toast, Toast.LENGTH_LONG).show();
// }
// flag++;
// } else {
// // 启动SDK
// ConcurrentHashMap<String, String> serverMap = new ConcurrentHashMap<String, String>();
//
// serverMap.put("openAPIInfo", TextUtils.isEmpty((String) GosDeploy.infoMap.get("openAPI_URL"))
// ? "api.gizwits.com" : (String) GosDeploy.infoMap.get("openAPI_URL"));
// serverMap.put("siteInfo", TextUtils.isEmpty((String) GosDeploy.infoMap.get("site_URL")) ? "site.gizwits.com"
// : (String) GosDeploy.infoMap.get("site_URL"));
// serverMap.put("pushInfo", (String) GosDeploy.infoMap.get("push_URL"));
// //GizWifiSDK.sharedInstance().startWithAppID(c, AppID, GosDeploy.setProductKeyList(), serverMap);
//
// GizWifiSDK.sharedInstance().startWithAppID(c, AppID, AppSecret, GosDeploy.setProductKeyList(), serverMap,
// false);
//
// }
// hand.sendEmptyMessageDelayed(SETCLOUD, 3000);
//
// }
//
// public static MessageCenter getInstance(Context c) {
// if (mCenter == null) {
// mCenter = new MessageCenter(c);
// }
// return mCenter;
// }
//
// Handler hand = new Handler() {
// public void handleMessage(android.os.Message msg) {
// GizWifiSDK.sharedInstance().setLogLevel(GizLogPrintLevel.GizLogPrintAll);
//
// };
// };
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.opensource.appkit.MessageCenter;
import com.gizwits.opensource.appkit.R;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView; | package com.gizwits.opensource.appkit.CommonModule;
public class GosBaseActivity extends FragmentActivity {
/** 设备热点默认密码 */
public static String SoftAP_PSW = "123456789";
/** 设备热点默认前缀 */
public static String SoftAP_Start = "XPG-GAgent";
/** 存储器默认名称 */
public static final String SPF_Name = "set";
/** Toast time */
public int toastTime = 2000;
/** 存储器 */
public SharedPreferences spf;
/** 等待框 */
public ProgressDialog progressDialog;
/** 标题栏 */
public ActionBar actionBar;
/** 实现WXEntryActivity与GosUserLoginActivity共用 */
public static Handler baseHandler;
public static boolean isclean = false;
public void setBaseHandler(Handler basehandler) {
if (null != basehandler) {
baseHandler = basehandler;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* 设置为竖屏
*/
if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE); | // Path: src/com/gizwits/opensource/appkit/MessageCenter.java
// public class MessageCenter {
// private static MessageCenter mCenter;
// int flag = 0;
//
// GosDeploy gosDeploy;
//
// private int SETCLOUD = 1111;
//
// private MessageCenter(Context c) {
// if (mCenter == null) {
// init(c);
// }
// }
//
// private void init(Context c) {
// gosDeploy = new GosDeploy(c);
// String AppID = GosDeploy.setAppID();
// String AppSecret = GosDeploy.setAppSecret();
// if (TextUtils.isEmpty(AppID) || AppID.contains("your_app_id") || TextUtils.isEmpty(AppSecret)
// || AppSecret.contains("your_app_secret")) {
// String AppID_Toast = c.getString(R.string.AppID_Toast);
// if (flag == 0) {
// Toast.makeText(c, AppID_Toast, Toast.LENGTH_LONG).show();
// }
// flag++;
// } else {
// // 启动SDK
// ConcurrentHashMap<String, String> serverMap = new ConcurrentHashMap<String, String>();
//
// serverMap.put("openAPIInfo", TextUtils.isEmpty((String) GosDeploy.infoMap.get("openAPI_URL"))
// ? "api.gizwits.com" : (String) GosDeploy.infoMap.get("openAPI_URL"));
// serverMap.put("siteInfo", TextUtils.isEmpty((String) GosDeploy.infoMap.get("site_URL")) ? "site.gizwits.com"
// : (String) GosDeploy.infoMap.get("site_URL"));
// serverMap.put("pushInfo", (String) GosDeploy.infoMap.get("push_URL"));
// //GizWifiSDK.sharedInstance().startWithAppID(c, AppID, GosDeploy.setProductKeyList(), serverMap);
//
// GizWifiSDK.sharedInstance().startWithAppID(c, AppID, AppSecret, GosDeploy.setProductKeyList(), serverMap,
// false);
//
// }
// hand.sendEmptyMessageDelayed(SETCLOUD, 3000);
//
// }
//
// public static MessageCenter getInstance(Context c) {
// if (mCenter == null) {
// mCenter = new MessageCenter(c);
// }
// return mCenter;
// }
//
// Handler hand = new Handler() {
// public void handleMessage(android.os.Message msg) {
// GizWifiSDK.sharedInstance().setLogLevel(GizLogPrintLevel.GizLogPrintAll);
//
// };
// };
//
// }
// Path: src/com/gizwits/opensource/appkit/CommonModule/GosBaseActivity.java
import java.util.ArrayList;
import java.util.List;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.opensource.appkit.MessageCenter;
import com.gizwits.opensource.appkit.R;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
package com.gizwits.opensource.appkit.CommonModule;
public class GosBaseActivity extends FragmentActivity {
/** 设备热点默认密码 */
public static String SoftAP_PSW = "123456789";
/** 设备热点默认前缀 */
public static String SoftAP_Start = "XPG-GAgent";
/** 存储器默认名称 */
public static final String SPF_Name = "set";
/** Toast time */
public int toastTime = 2000;
/** 存储器 */
public SharedPreferences spf;
/** 等待框 */
public ProgressDialog progressDialog;
/** 标题栏 */
public ActionBar actionBar;
/** 实现WXEntryActivity与GosUserLoginActivity共用 */
public static Handler baseHandler;
public static boolean isclean = false;
public void setBaseHandler(Handler basehandler) {
if (null != basehandler) {
baseHandler = basehandler;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* 设置为竖屏
*/
if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE); | MessageCenter.getInstance(this); |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/CommonModule/GosDeploy.java | // Path: src/com/gizwits/opensource/appkit/utils/AssetsUtils.java
// public class AssetsUtils {
//
// public static void assetsDataToSD(String fileOutPutName,
// String fileInPutName, Context context) throws IOException {
// InputStream myInput;
// File file = new File(fileOutPutName);
// /*if (!file.exists()) {
// file.createNewFile();
// }else {
// return;
// }*/
// OutputStream myOutput = new FileOutputStream(fileOutPutName);
// myInput = context.getAssets().open(fileInPutName);
// byte[] buffer = new byte[1024];
// int length = myInput.read(buffer);
// while (length > 0) {
// myOutput.write(buffer, 0, length);
// length = myInput.read(buffer);
// }
//
// myOutput.flush();
// myInput.close();
// myOutput.close();
// }
//
//
//
// public static void saveFile(String str) {
// String filePath = null;
//
//
// filePath = GosDeploy.fileOutName;
// try {
// if(filePath!=null){
// File file = new File(filePath);
// if (!file.exists()) {
// File dir = new File(file.getParent());
// dir.mkdirs();
// file.createNewFile();
// }
// FileOutputStream outStream = new FileOutputStream(file);
// outStream.write(str.getBytes());
// outStream.close();
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// }
| import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.utils.AssetsUtils;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast; | }
@SuppressWarnings("rawtypes")
private void setMap(StringBuilder stringBuilder) {
infoMap = new HashMap<String, Object>();
try {
JSONObject root = new JSONObject(stringBuilder.toString());
Iterator actions = root.keys();
while (actions.hasNext()) {
String param = actions.next().toString();
if (param.equals("product_key")) {
JSONArray myarray = (JSONArray) root.get(param);
infoMap.put(param, myarray);
} else {
Object value = root.get(param);
infoMap.put(param, value);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// 拷贝json文件
private void copyJson() {
try { | // Path: src/com/gizwits/opensource/appkit/utils/AssetsUtils.java
// public class AssetsUtils {
//
// public static void assetsDataToSD(String fileOutPutName,
// String fileInPutName, Context context) throws IOException {
// InputStream myInput;
// File file = new File(fileOutPutName);
// /*if (!file.exists()) {
// file.createNewFile();
// }else {
// return;
// }*/
// OutputStream myOutput = new FileOutputStream(fileOutPutName);
// myInput = context.getAssets().open(fileInPutName);
// byte[] buffer = new byte[1024];
// int length = myInput.read(buffer);
// while (length > 0) {
// myOutput.write(buffer, 0, length);
// length = myInput.read(buffer);
// }
//
// myOutput.flush();
// myInput.close();
// myOutput.close();
// }
//
//
//
// public static void saveFile(String str) {
// String filePath = null;
//
//
// filePath = GosDeploy.fileOutName;
// try {
// if(filePath!=null){
// File file = new File(filePath);
// if (!file.exists()) {
// File dir = new File(file.getParent());
// dir.mkdirs();
// file.createNewFile();
// }
// FileOutputStream outStream = new FileOutputStream(file);
// outStream.write(str.getBytes());
// outStream.close();
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// }
// Path: src/com/gizwits/opensource/appkit/CommonModule/GosDeploy.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.utils.AssetsUtils;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
}
@SuppressWarnings("rawtypes")
private void setMap(StringBuilder stringBuilder) {
infoMap = new HashMap<String, Object>();
try {
JSONObject root = new JSONObject(stringBuilder.toString());
Iterator actions = root.keys();
while (actions.hasNext()) {
String param = actions.next().toString();
if (param.equals("product_key")) {
JSONArray myarray = (JSONArray) root.get(param);
infoMap.put(param, myarray);
} else {
Object value = root.get(param);
infoMap.put(param, value);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// 拷贝json文件
private void copyJson() {
try { | AssetsUtils.assetsDataToSD(fileOutName, fileName, context); |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceActivity.java | // Path: src/com/gizwits/opensource/appkit/CommonModule/GosConstant.java
// public class GosConstant {
//
// public static List<ScanResult> ssidList = new ArrayList<ScanResult>();
//
// public static int nowPager = -1;
//
// public static List<GizUserInfo> mybindUsers = new ArrayList<GizUserInfo>();
//
// public static List<GizDeviceSharingInfo> mydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static List<GizDeviceSharingInfo> newmydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static boolean isEdit = false;
//
// public static String mozu = "https://item.taobao.com/item.htm?spm=686.1000925.0.0.nPcYfD&id=542479181481";
//
// // 设备热点默认密码
// public static final String SoftAP_PSW = "123456789";
//
//
// // 设备热点默认前缀
// public static final String SoftAP_Start = "XPG-GAgent";
//
// }
| import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosConstant;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView; | package com.gizwits.opensource.appkit.ConfigModule;
@SuppressLint({ "InflateParams", "HandlerLeak" })
public class GosChooseDeviceActivity extends GosConfigModuleBaseActivity implements OnClickListener {
/** The tv Nodevice */
TextView tvNodevice;
/** The list View */
ListView listView;
/** 系统WiFi集合 */
ArrayList<ScanResult> list;
/** 设备热点集合 */
ArrayList<ScanResult> softList;
/** 适配器 */
Myadapter myadapter;
/** 计时器 */
Timer timer;
int flag = 0;
private enum handler_key {
/** 刷新列表 */
UPDATALIST,
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
handler_key key = handler_key.values()[msg.what];
switch (key) {
// 更新列表
case UPDATALIST:
initData();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gos_choose_device);
// 设置ActionBar
setActionBar(true, true, R.string.choosedevice);
initView();
initEvent();
}
@Override
protected void onResume() {
super.onResume();
startTimer();
}
@Override
public void onPause() {
super.onPause();
timer.cancel();
}
private void initData() {
list = new ArrayList<ScanResult>(); | // Path: src/com/gizwits/opensource/appkit/CommonModule/GosConstant.java
// public class GosConstant {
//
// public static List<ScanResult> ssidList = new ArrayList<ScanResult>();
//
// public static int nowPager = -1;
//
// public static List<GizUserInfo> mybindUsers = new ArrayList<GizUserInfo>();
//
// public static List<GizDeviceSharingInfo> mydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static List<GizDeviceSharingInfo> newmydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();
//
// public static boolean isEdit = false;
//
// public static String mozu = "https://item.taobao.com/item.htm?spm=686.1000925.0.0.nPcYfD&id=542479181481";
//
// // 设备热点默认密码
// public static final String SoftAP_PSW = "123456789";
//
//
// // 设备热点默认前缀
// public static final String SoftAP_Start = "XPG-GAgent";
//
// }
// Path: src/com/gizwits/opensource/appkit/ConfigModule/GosChooseDeviceActivity.java
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosConstant;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
package com.gizwits.opensource.appkit.ConfigModule;
@SuppressLint({ "InflateParams", "HandlerLeak" })
public class GosChooseDeviceActivity extends GosConfigModuleBaseActivity implements OnClickListener {
/** The tv Nodevice */
TextView tvNodevice;
/** The list View */
ListView listView;
/** 系统WiFi集合 */
ArrayList<ScanResult> list;
/** 设备热点集合 */
ArrayList<ScanResult> softList;
/** 适配器 */
Myadapter myadapter;
/** 计时器 */
Timer timer;
int flag = 0;
private enum handler_key {
/** 刷新列表 */
UPDATALIST,
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
handler_key key = handler_key.values()[msg.what];
switch (key) {
// 更新列表
case UPDATALIST:
initData();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gos_choose_device);
// 设置ActionBar
setActionBar(true, true, R.string.choosedevice);
initView();
initEvent();
}
@Override
protected void onResume() {
super.onResume();
startTimer();
}
@Override
public void onPause() {
super.onPause();
timer.cancel();
}
private void initData() {
list = new ArrayList<ScanResult>(); | list = (ArrayList<ScanResult>) GosConstant.ssidList; |
hhaslam11/Text-Fighter | src/com/hotmail/kalebmarc/textfighter/main/EnemyTest.java | // Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
| import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.hotmail.kalebmarc.textfighter.player.Xp; | rifle = new Weapon("Rifle", 1, 18, true, 275, 1, 5, 10, 1.25, 6, 7, true, false);
sniper = new Weapon("Sniper", 1, 10, true, 700, 2, 7, 0, 1, 7, 10, true, false);
Weapon.arrayWeapon.get(Weapon.getIndex(baseballBat)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).setAmmo(4, true);
darkElf = new Enemy("Dark Elf", 45, 10, 15, 10, 15, 15, 5, 99, true, false);
ninja = new Enemy("Ninja", 75, 5, 15, 5, 15, 15, 1, 10, true, false);
giantSpider = new Enemy("Giant Spider", 35, 5, 10, 5, 10, 10, 5, 99, true, false);
zombie = new Enemy("Zombie", 20, 5, 15, 5, 15, 15, 1, 10, true, false);
goblin = new Enemy("Goblin", 60, 10, 20, 10, 20, 20, 1, 10, true, false);
ghost = new Enemy("Ghost", 85, 15, 25, 15, 25, 25, 1, 99, true, false);
barbarian = new Enemy("Barbarian", 50, 5, 15, 5, 15, 15, 5, 99, true, false);
giantAnt = new Enemy("Giant Ant", 30, 5, 10, 5, 10, 10, 1, 10, true, false);
evilUnicorn = new Enemy("Evil Unicorn", 35, 30, 40, 5, 15, 20, 5, 99, true, false);
ogre = new Enemy("Ogre", 90, 20, 50, 10, 30, 50, 5, 99, true, false);
allEnemies = new ArrayList<>();
allEnemies.add(darkElf);
allEnemies.add(ninja);
allEnemies.add(giantSpider);
allEnemies.add(zombie);
allEnemies.add(ghost);
allEnemies.add(barbarian);
allEnemies.add(giantAnt);
allEnemies.add(evilUnicorn);
allEnemies.add(ogre);
| // Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
// Path: src/com/hotmail/kalebmarc/textfighter/main/EnemyTest.java
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.hotmail.kalebmarc.textfighter.player.Xp;
rifle = new Weapon("Rifle", 1, 18, true, 275, 1, 5, 10, 1.25, 6, 7, true, false);
sniper = new Weapon("Sniper", 1, 10, true, 700, 2, 7, 0, 1, 7, 10, true, false);
Weapon.arrayWeapon.get(Weapon.getIndex(baseballBat)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).setAmmo(4, true);
darkElf = new Enemy("Dark Elf", 45, 10, 15, 10, 15, 15, 5, 99, true, false);
ninja = new Enemy("Ninja", 75, 5, 15, 5, 15, 15, 1, 10, true, false);
giantSpider = new Enemy("Giant Spider", 35, 5, 10, 5, 10, 10, 5, 99, true, false);
zombie = new Enemy("Zombie", 20, 5, 15, 5, 15, 15, 1, 10, true, false);
goblin = new Enemy("Goblin", 60, 10, 20, 10, 20, 20, 1, 10, true, false);
ghost = new Enemy("Ghost", 85, 15, 25, 15, 25, 25, 1, 99, true, false);
barbarian = new Enemy("Barbarian", 50, 5, 15, 5, 15, 15, 5, 99, true, false);
giantAnt = new Enemy("Giant Ant", 30, 5, 10, 5, 10, 10, 1, 10, true, false);
evilUnicorn = new Enemy("Evil Unicorn", 35, 30, 40, 5, 15, 20, 5, 99, true, false);
ogre = new Enemy("Ogre", 90, 20, 50, 10, 30, 50, 5, 99, true, false);
allEnemies = new ArrayList<>();
allEnemies.add(darkElf);
allEnemies.add(ninja);
allEnemies.add(giantSpider);
allEnemies.add(zombie);
allEnemies.add(ghost);
allEnemies.add(barbarian);
allEnemies.add(giantAnt);
allEnemies.add(evilUnicorn);
allEnemies.add(ogre);
| Xp.setLevel(1); |
hhaslam11/Text-Fighter | src/com/hotmail/kalebmarc/textfighter/main/WeaponTest.java | // Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
| import com.hotmail.kalebmarc.textfighter.player.Xp;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | sysInBackup = System.in; // backup System.in to restore it later
fists = new Weapon("Fists", true, false, 0, 0, 5, 10, true, false);
baseballBat = new Weapon("Baseball Bat", false, true, 120, 1, 10, 15, true, false);
knife = new Weapon("Knife", false, true, 125, 2, 10, 20, true, false);
pipe = new Weapon("Pipe", false, false, 0, 0, 5, 20, true, false);
//Guns:
pistol = new Weapon("Pistol", 1, 18, true, 250, 1, 4, 15, 1.5, 3, 4, true, false);
smg = new Weapon("Smg", 10, 75, true, 700, 1, 10, 75, 2.5, 4, 6, true, false);
shotgun = new Weapon("Shotgun", 1, 12, true, 375, 2, 9, 60, 2, 5, 7, true, false);
rifle = new Weapon("Rifle", 1, 18, true, 275, 1, 5, 10, 1.25, 6, 7, true, false);
sniper = new Weapon("Sniper", 1, 10, true, 700, 2, 7, 0, 1, 7, 10, true, false);
Weapon.arrayWeapon.get(1).owns = true;
Weapon.arrayWeapon.get(4).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(baseballBat)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).setAmmo(4, true);
darkElf = new Enemy("Dark Elf", 145, 10, 15, 10, 15, 15, 5, 100, true, false);
ninja = new Enemy("Ninja", 175, 5, 15, 5, 15, 15, 1, 10, true, false);
giantSpider = new Enemy("Giant Spider", 135, 5, 10, 5, 10, 10, 5, 100, true, false);
zombie = new Enemy("Zombie", 120, 5, 15, 5, 15, 15, 1, 10, true, false);
goblin = new Enemy("Goblin", 160, 10, 20, 10, 20, 20, 1, 10, true, false);
ghost = new Enemy("Ghost", 185, 15, 25, 15, 25, 25, 1, 100, true, false);
barbarian = new Enemy("Barbarian", 150, 5, 15, 5, 15, 15, 5, 100, true, false);
giantAnt = new Enemy("Giant Ant", 130, 5, 10, 5, 10, 10, 1, 10, true, false);
evilUnicorn = new Enemy("Evil Unicorn", 135, 30, 40, 5, 15, 20, 5, 100, true, false);
ogre = new Enemy("Ogre", 190, 20, 50, 10, 30, 50, 5, 100, true, false);
| // Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
// Path: src/com/hotmail/kalebmarc/textfighter/main/WeaponTest.java
import com.hotmail.kalebmarc.textfighter.player.Xp;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
sysInBackup = System.in; // backup System.in to restore it later
fists = new Weapon("Fists", true, false, 0, 0, 5, 10, true, false);
baseballBat = new Weapon("Baseball Bat", false, true, 120, 1, 10, 15, true, false);
knife = new Weapon("Knife", false, true, 125, 2, 10, 20, true, false);
pipe = new Weapon("Pipe", false, false, 0, 0, 5, 20, true, false);
//Guns:
pistol = new Weapon("Pistol", 1, 18, true, 250, 1, 4, 15, 1.5, 3, 4, true, false);
smg = new Weapon("Smg", 10, 75, true, 700, 1, 10, 75, 2.5, 4, 6, true, false);
shotgun = new Weapon("Shotgun", 1, 12, true, 375, 2, 9, 60, 2, 5, 7, true, false);
rifle = new Weapon("Rifle", 1, 18, true, 275, 1, 5, 10, 1.25, 6, 7, true, false);
sniper = new Weapon("Sniper", 1, 10, true, 700, 2, 7, 0, 1, 7, 10, true, false);
Weapon.arrayWeapon.get(1).owns = true;
Weapon.arrayWeapon.get(4).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(baseballBat)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).owns = true;
Weapon.arrayWeapon.get(Weapon.getIndex(pistol)).setAmmo(4, true);
darkElf = new Enemy("Dark Elf", 145, 10, 15, 10, 15, 15, 5, 100, true, false);
ninja = new Enemy("Ninja", 175, 5, 15, 5, 15, 15, 1, 10, true, false);
giantSpider = new Enemy("Giant Spider", 135, 5, 10, 5, 10, 10, 5, 100, true, false);
zombie = new Enemy("Zombie", 120, 5, 15, 5, 15, 15, 1, 10, true, false);
goblin = new Enemy("Goblin", 160, 10, 20, 10, 20, 20, 1, 10, true, false);
ghost = new Enemy("Ghost", 185, 15, 25, 15, 25, 25, 1, 100, true, false);
barbarian = new Enemy("Barbarian", 150, 5, 15, 5, 15, 15, 5, 100, true, false);
giantAnt = new Enemy("Giant Ant", 130, 5, 10, 5, 10, 10, 1, 10, true, false);
evilUnicorn = new Enemy("Evil Unicorn", 135, 30, 40, 5, 15, 20, 5, 100, true, false);
ogre = new Enemy("Ogre", 190, 20, 50, 10, 30, 50, 5, 100, true, false);
| Xp.setLevel(1); |
hhaslam11/Text-Fighter | src/tests/TestGameClock.java | // Path: src/time/GameClock.java
// public class GameClock {
//
//
// private static LocalDateTime baseTime;
// private static LocalDateTime fastTime;
// private static long startTime;
// private static long endTime;
// private static long increasedTime;
// // Maybe where we set increasePercent could be moved to Settings?
// private static double increasePercent = 0.5; // Time increase can be changed to desired increase.
// private static DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("E, MMM dd yyyy-HH:mm:ss");
// private static String gameDate;
// private static String gameTime;
//
//
// // Default constructor
// public GameClock() {
//
// }
//
// // Declares the base time of the players current time.
// public static void startTimeClock() {
// startTime = System.currentTimeMillis();
// baseTime = LocalDateTime.now();
// }
//
// // This method is used as a end time place holder so that we can get a time duration.
// public static void endTimeCounter() {
// endTime = System.currentTimeMillis();
// }
//
// // The time increase is based off of getting the milliseconds and increasing it by a percentage.
// // This method returns the amount of time in milliseconds that the game clock needs to be increased.
// public static long timeConversion() {
// increasedTime = endTime - startTime;
// return (long) (increasedTime + (increasedTime * increasePercent));
// }
//
// // This method adds the increased time to the base time.
// // The base time gets formatted into a string.
// // The date and time string gets split into two separate date and time strings.
// public static void updateGameTime() {
// endTimeCounter();
// fastTime = baseTime.plus(Duration.ofMillis(timeConversion()));
// splitDateTime(fastTime);
// }
//
// // This method is for simply splitting up the LocalDateTime into separate strings of date and time.
// public static void splitDateTime(LocalDateTime dateTime) {
// String[] dateTimeArray = dateTime.format(myFormatObj).split("-");
// gameDate = dateTimeArray[0];
// gameTime = dateTimeArray[1];
// }
//
//
//
//
// // All these methods below are getters and setters for the variables.
// // These will be used mainly for testing purposes.
//
// public LocalDateTime getBaseTime() {
// return GameClock.baseTime;
// }
//
// public void setBaseTime(LocalDateTime newBaseTime) {
// GameClock.baseTime = newBaseTime;
// }
//
// public LocalDateTime getFastTime() {
// return GameClock.fastTime;
// }
//
// public void setFastTime(LocalDateTime newFastTime) {
// GameClock.fastTime = newFastTime;
// }
//
// public long getStartTime() {
// return GameClock.startTime;
// }
//
// public void setStartTime(long newStartTime) {
// GameClock.startTime = newStartTime;
// }
//
// public long getEndTime() {
// return GameClock.endTime;
// }
//
// public void setEndTime(long newEndTime) {
// GameClock.endTime = newEndTime;
// }
//
// public long getIncreasedTime() {
// return GameClock.increasedTime;
// }
//
// public double getIncreasePercent() {
// return GameClock.increasePercent;
// }
//
// public DateTimeFormatter getDateTimeFormat() {
// return GameClock.myFormatObj;
// }
//
// // The getter and setter methods below here are static so that they can be used from the Game class to grab
// // the date and time as separate strings.
// public static void setGameDate(String date) {
// GameClock.gameDate = date;
// }
//
// public static String getGameDate() {
// return GameClock.gameDate;
// }
//
// public static void setGameTime(String time) {
// GameClock.gameTime = time;
// }
//
// public static String getGameTime() {
// return GameClock.gameTime;
// }
//
//
// }
| import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
import time.GameClock; | package tests;
public class TestGameClock {
@Test
void testTimeConversion() { | // Path: src/time/GameClock.java
// public class GameClock {
//
//
// private static LocalDateTime baseTime;
// private static LocalDateTime fastTime;
// private static long startTime;
// private static long endTime;
// private static long increasedTime;
// // Maybe where we set increasePercent could be moved to Settings?
// private static double increasePercent = 0.5; // Time increase can be changed to desired increase.
// private static DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("E, MMM dd yyyy-HH:mm:ss");
// private static String gameDate;
// private static String gameTime;
//
//
// // Default constructor
// public GameClock() {
//
// }
//
// // Declares the base time of the players current time.
// public static void startTimeClock() {
// startTime = System.currentTimeMillis();
// baseTime = LocalDateTime.now();
// }
//
// // This method is used as a end time place holder so that we can get a time duration.
// public static void endTimeCounter() {
// endTime = System.currentTimeMillis();
// }
//
// // The time increase is based off of getting the milliseconds and increasing it by a percentage.
// // This method returns the amount of time in milliseconds that the game clock needs to be increased.
// public static long timeConversion() {
// increasedTime = endTime - startTime;
// return (long) (increasedTime + (increasedTime * increasePercent));
// }
//
// // This method adds the increased time to the base time.
// // The base time gets formatted into a string.
// // The date and time string gets split into two separate date and time strings.
// public static void updateGameTime() {
// endTimeCounter();
// fastTime = baseTime.plus(Duration.ofMillis(timeConversion()));
// splitDateTime(fastTime);
// }
//
// // This method is for simply splitting up the LocalDateTime into separate strings of date and time.
// public static void splitDateTime(LocalDateTime dateTime) {
// String[] dateTimeArray = dateTime.format(myFormatObj).split("-");
// gameDate = dateTimeArray[0];
// gameTime = dateTimeArray[1];
// }
//
//
//
//
// // All these methods below are getters and setters for the variables.
// // These will be used mainly for testing purposes.
//
// public LocalDateTime getBaseTime() {
// return GameClock.baseTime;
// }
//
// public void setBaseTime(LocalDateTime newBaseTime) {
// GameClock.baseTime = newBaseTime;
// }
//
// public LocalDateTime getFastTime() {
// return GameClock.fastTime;
// }
//
// public void setFastTime(LocalDateTime newFastTime) {
// GameClock.fastTime = newFastTime;
// }
//
// public long getStartTime() {
// return GameClock.startTime;
// }
//
// public void setStartTime(long newStartTime) {
// GameClock.startTime = newStartTime;
// }
//
// public long getEndTime() {
// return GameClock.endTime;
// }
//
// public void setEndTime(long newEndTime) {
// GameClock.endTime = newEndTime;
// }
//
// public long getIncreasedTime() {
// return GameClock.increasedTime;
// }
//
// public double getIncreasePercent() {
// return GameClock.increasePercent;
// }
//
// public DateTimeFormatter getDateTimeFormat() {
// return GameClock.myFormatObj;
// }
//
// // The getter and setter methods below here are static so that they can be used from the Game class to grab
// // the date and time as separate strings.
// public static void setGameDate(String date) {
// GameClock.gameDate = date;
// }
//
// public static String getGameDate() {
// return GameClock.gameDate;
// }
//
// public static void setGameTime(String time) {
// GameClock.gameTime = time;
// }
//
// public static String getGameTime() {
// return GameClock.gameTime;
// }
//
//
// }
// Path: src/tests/TestGameClock.java
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
import time.GameClock;
package tests;
public class TestGameClock {
@Test
void testTimeConversion() { | GameClock newClock = new GameClock(); |
hhaslam11/Text-Fighter | src/com/hotmail/kalebmarc/textfighter/main/Loan.java | // Path: src/com/hotmail/kalebmarc/textfighter/player/Coins.java
// public class Coins {
//
// private static int coins;
// private static int bank;
//
//
// private Coins() {
// }
//
// public static int get() {
// return coins;
// }
//
// public static void set(int amount, boolean add) {
// if (!add) {
// coins = amount;
// } else {
// coins += amount;
// if (amount < 0) Stats.totalCoinsSpent += -amount;
// if (coins < 0) coins = 0;
// }
// }
//
// }
//
// Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
| import com.hotmail.kalebmarc.textfighter.player.Coins;
import com.hotmail.kalebmarc.textfighter.player.Xp; | break;
case 3:
return;
}
}
}
private static void createLoan() {
if (hasLoan()) {
Ui.msg("You can not request a loan while you already have one.");
return;
}
Ui.cls();
Ui.println("Enter the amount you would like");
Ui.println("to borrow.");
Ui.println("Your max amount allowed is " + getMaxLoan());
int request = Ui.getValidInt();
if (request > getMaxLoan()) {
Ui.msg("Your max amount you can borrow is " + getMaxLoan() + "!");
return;
}
if (request <= 0) {
Ui.msg("You must enter at least 1 coin.");
return;
}
//Give loan | // Path: src/com/hotmail/kalebmarc/textfighter/player/Coins.java
// public class Coins {
//
// private static int coins;
// private static int bank;
//
//
// private Coins() {
// }
//
// public static int get() {
// return coins;
// }
//
// public static void set(int amount, boolean add) {
// if (!add) {
// coins = amount;
// } else {
// coins += amount;
// if (amount < 0) Stats.totalCoinsSpent += -amount;
// if (coins < 0) coins = 0;
// }
// }
//
// }
//
// Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
// Path: src/com/hotmail/kalebmarc/textfighter/main/Loan.java
import com.hotmail.kalebmarc.textfighter.player.Coins;
import com.hotmail.kalebmarc.textfighter.player.Xp;
break;
case 3:
return;
}
}
}
private static void createLoan() {
if (hasLoan()) {
Ui.msg("You can not request a loan while you already have one.");
return;
}
Ui.cls();
Ui.println("Enter the amount you would like");
Ui.println("to borrow.");
Ui.println("Your max amount allowed is " + getMaxLoan());
int request = Ui.getValidInt();
if (request > getMaxLoan()) {
Ui.msg("Your max amount you can borrow is " + getMaxLoan() + "!");
return;
}
if (request <= 0) {
Ui.msg("You must enter at least 1 coin.");
return;
}
//Give loan | Coins.set(request, true); |
hhaslam11/Text-Fighter | src/com/hotmail/kalebmarc/textfighter/main/Loan.java | // Path: src/com/hotmail/kalebmarc/textfighter/player/Coins.java
// public class Coins {
//
// private static int coins;
// private static int bank;
//
//
// private Coins() {
// }
//
// public static int get() {
// return coins;
// }
//
// public static void set(int amount, boolean add) {
// if (!add) {
// coins = amount;
// } else {
// coins += amount;
// if (amount < 0) Stats.totalCoinsSpent += -amount;
// if (coins < 0) coins = 0;
// }
// }
//
// }
//
// Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
| import com.hotmail.kalebmarc.textfighter.player.Coins;
import com.hotmail.kalebmarc.textfighter.player.Xp; | Ui.println("You will not be able to deposit coins into the bank until your loan is fully paid off.");
Ui.println("How much would you like to pay off?");
int amountToPay = Ui.getValidInt();
Ui.cls();
if (Coins.get() < amountToPay) {
Ui.println("You don't have enough coins.");
Ui.pause();
return;
}
if (amountToPay <= 0) {
Ui.println("You must enter at least 1 coin.");
Ui.pause();
return;
}
if (amountToPay > getGrossDue()) {
Ui.println("You only owe " + getGrossDue() + "! Enter a small amount");
Ui.pause();
}
netDue = getGrossDue() - amountToPay;
Coins.set(-amountToPay, true);
Ui.println("You have paid back " + amountToPay + " coins.\nYou now have " + getGrossDue() + " left to pay.");
if (getGrossDue() == 0) currentLoan = 0;
Ui.pause();
}
private static int getMaxLoan() { | // Path: src/com/hotmail/kalebmarc/textfighter/player/Coins.java
// public class Coins {
//
// private static int coins;
// private static int bank;
//
//
// private Coins() {
// }
//
// public static int get() {
// return coins;
// }
//
// public static void set(int amount, boolean add) {
// if (!add) {
// coins = amount;
// } else {
// coins += amount;
// if (amount < 0) Stats.totalCoinsSpent += -amount;
// if (coins < 0) coins = 0;
// }
// }
//
// }
//
// Path: src/com/hotmail/kalebmarc/textfighter/player/Xp.java
// public class Xp {
//
// //Variables
// private static int xp;
// private static int battleXp;
// private static int xpNeeded;
// private static int level;
// public static int total;
//
// private Xp() {
// }
//
// private static void levelUp() {
// if (level == 9) {
// Ui.popup("You've reached level 10!\nYou have been rewarded 250 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// level = 10;
// Coins.set(250, true);
//
// }else if(level > 100){
// Handle.error("Error - Level is greater than 100");
// level = 100;
// }else if(level == 99){
// level = 100;
// xp = 49000;
// }else {
//
// Ui.popup("You've leveled up! You are now level " + (level + 1) + "!\nYou have been rewarded 100 coins!", "Level Up!", JOptionPane.INFORMATION_MESSAGE);
// xp = 0;
// xpNeeded += 500;
// level++;
// Coins.set(100, true);
// }
// Achievements.check();
// }
//
// public static void set(int amount, boolean add) {
//
// if((level == 100) || Cheats.enabled()){
// return;
// }
// if (add){
// xp += amount;
// total += amount;
// } else {
// xp = amount;
// }
// if ((xp >= xpNeeded) && (xpNeeded != 0)){// (xpNeeded != 0) is so it doesn't try and level up when cheats are enabled (Which sets xp and xpNeeded to 0)
// int leftOverXp = xp - xpNeeded;
// levelUp();
// set(leftOverXp, true);
// }
//
// }
//
// public static int getBattleXp() {
// return battleXp;
// }
//
// public static void setBattleXp(int amount, boolean add) {
// if(add) {
// battleXp += amount;
// } else {
// battleXp = amount;
// }
// }
//
// public static void setLevel(int lvl){
// level = lvl;
// }
//
// public static void setOutOf(int outOf){
// xpNeeded = outOf;
// }
// public static void setAll(int current, int outOf, int lvl){
// xp = current;
// xpNeeded = outOf;
// level = lvl;
// }
//
// public static int get(){
// return xp;
// }
//
// public static int getOutOf(){
// return xpNeeded;
// }
//
// public static int getLevel(){
// return level;
// }
//
// public static String getFull(){
// return xp + "/" + xpNeeded + " xp";
// }
// }
// Path: src/com/hotmail/kalebmarc/textfighter/main/Loan.java
import com.hotmail.kalebmarc.textfighter.player.Coins;
import com.hotmail.kalebmarc.textfighter.player.Xp;
Ui.println("You will not be able to deposit coins into the bank until your loan is fully paid off.");
Ui.println("How much would you like to pay off?");
int amountToPay = Ui.getValidInt();
Ui.cls();
if (Coins.get() < amountToPay) {
Ui.println("You don't have enough coins.");
Ui.pause();
return;
}
if (amountToPay <= 0) {
Ui.println("You must enter at least 1 coin.");
Ui.pause();
return;
}
if (amountToPay > getGrossDue()) {
Ui.println("You only owe " + getGrossDue() + "! Enter a small amount");
Ui.pause();
}
netDue = getGrossDue() - amountToPay;
Coins.set(-amountToPay, true);
Ui.println("You have paid back " + amountToPay + " coins.\nYou now have " + getGrossDue() + " left to pay.");
if (getGrossDue() == 0) currentLoan = 0;
Ui.pause();
}
private static int getMaxLoan() { | return Xp.getLevel() * 100; |
pnerg/java-scala-util | src/main/java/javascalautils/concurrent/ExecutorImpl.java | // Path: src/main/java/javascalautils/concurrent/PromiseCompanion.java
// public static <T> Promise<T> Promise() {
// return Promise.apply();
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import static javascalautils.concurrent.PromiseCompanion.Promise; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils.concurrent;
/**
* Implements the executor interface. <br>
* Internally uses a Java concurrent executor to provide the thread execution mechanism.
*
* @author Peter Nerg
* @since 1.2
*/
final class ExecutorImpl implements Executor {
/** The internal Java concurrent executor to perform the actual work. */
private final java.util.concurrent.Executor executor;
/**
* Creates an instance using the provided SDK {@link java.util.concurrent.Executor} for thread
* management.
*
* @param executor The underlying executor to use
* @since 1.2
*/
ExecutorImpl(java.util.concurrent.Executor executor) {
this.executor = executor;
}
/*
* (non-Javadoc)
*
* @see javascalautils.concurrent.Executor#execute(javascalautils.concurrent.Executable)
*/
@Override
public <T> Future<T> execute(final Executable<T> executable) { | // Path: src/main/java/javascalautils/concurrent/PromiseCompanion.java
// public static <T> Promise<T> Promise() {
// return Promise.apply();
// }
// Path: src/main/java/javascalautils/concurrent/ExecutorImpl.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import static javascalautils.concurrent.PromiseCompanion.Promise;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils.concurrent;
/**
* Implements the executor interface. <br>
* Internally uses a Java concurrent executor to provide the thread execution mechanism.
*
* @author Peter Nerg
* @since 1.2
*/
final class ExecutorImpl implements Executor {
/** The internal Java concurrent executor to perform the actual work. */
private final java.util.concurrent.Executor executor;
/**
* Creates an instance using the provided SDK {@link java.util.concurrent.Executor} for thread
* management.
*
* @param executor The underlying executor to use
* @since 1.2
*/
ExecutorImpl(java.util.concurrent.Executor executor) {
this.executor = executor;
}
/*
* (non-Javadoc)
*
* @see javascalautils.concurrent.Executor#execute(javascalautils.concurrent.Executable)
*/
@Override
public <T> Future<T> execute(final Executable<T> executable) { | final Promise<T> promise = Promise(); |
pnerg/java-scala-util | src/main/java/javascalautils/Some.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right; | * Returns an Option consisting of the result of applying the given function to the current value.
*
* @since 1.2
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
try {
return function.apply(value);
} catch (Throwable ex) {
throw new BrokenFunctionException("Caught exception while applying function", ex);
}
}
/**
* Always returns <i>this</i>.
*
* @since 1.0
*/
@Override
public Option<T> orElse(Supplier<Option<T>> s) {
return this;
}
/**
* Returns a {@link Left} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/Some.java
import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
* Returns an Option consisting of the result of applying the given function to the current value.
*
* @since 1.2
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
try {
return function.apply(value);
} catch (Throwable ex) {
throw new BrokenFunctionException("Caught exception while applying function", ex);
}
}
/**
* Always returns <i>this</i>.
*
* @since 1.0
*/
@Override
public Option<T> orElse(Supplier<Option<T>> s) {
return this;
}
/**
* Returns a {@link Left} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) { | return Left(value); |
pnerg/java-scala-util | src/main/java/javascalautils/Some.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right; | }
}
/**
* Always returns <i>this</i>.
*
* @since 1.0
*/
@Override
public Option<T> orElse(Supplier<Option<T>> s) {
return this;
}
/**
* Returns a {@link Left} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) {
return Left(value);
}
/**
* Returns a {@link Right} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <L> Either<L, T> toRight(Supplier<L> left) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/Some.java
import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
}
}
/**
* Always returns <i>this</i>.
*
* @since 1.0
*/
@Override
public Option<T> orElse(Supplier<Option<T>> s) {
return this;
}
/**
* Returns a {@link Left} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) {
return Left(value);
}
/**
* Returns a {@link Right} containing the value of this instance.
*
* @since 1.4
*/
@Override
public <L> Either<L, T> toRight(Supplier<L> left) { | return Right(value); |
pnerg/java-scala-util | src/main/java/javascalautils/Left.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.util.function.Function;
import static javascalautils.EitherCompanion.Right;
import java.io.Serializable; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the {@link Left} side of an {@link Either}.
*
* @author Peter Nerg
* @since 1.1
* @param <L> The type for the {@link Left} side
* @param <R> The type for the {@link Right} side (not used for this class)
*/
public final class Left<L, R> implements Either<L, R>, Serializable {
private static final long serialVersionUID = 6415576974626280469L;
private final L value;
/**
* Creates an instance wrapping the provide value.
*
* @param value The value wrapped by this instance
* @since 1.1
*/
public Left(L value) {
this.value = value;
}
/**
* Applies the provided <code>func_left</code> to the wrapped value and returns the result.
*
* @since 1.1
*/
@Override
public <T> T fold(Function<L, T> func_left, Function<R, T> func_right) {
return func_left.apply(value);
}
/**
* Always returns <code>false</code>.
*
* @since 1.1
*/
@Override
public boolean isRight() {
return false;
}
/**
* Returns a {@link Right} containing the value for this instance.
*
* @since 1.1
*/
@Override
public Either<R, L> swap() { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/Left.java
import java.util.function.Function;
import static javascalautils.EitherCompanion.Right;
import java.io.Serializable;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the {@link Left} side of an {@link Either}.
*
* @author Peter Nerg
* @since 1.1
* @param <L> The type for the {@link Left} side
* @param <R> The type for the {@link Right} side (not used for this class)
*/
public final class Left<L, R> implements Either<L, R>, Serializable {
private static final long serialVersionUID = 6415576974626280469L;
private final L value;
/**
* Creates an instance wrapping the provide value.
*
* @param value The value wrapped by this instance
* @since 1.1
*/
public Left(L value) {
this.value = value;
}
/**
* Applies the provided <code>func_left</code> to the wrapped value and returns the result.
*
* @since 1.1
*/
@Override
public <T> T fold(Function<L, T> func_left, Function<R, T> func_right) {
return func_left.apply(value);
}
/**
* Always returns <code>false</code>.
*
* @since 1.1
*/
@Override
public boolean isRight() {
return false;
}
/**
* Returns a {@link Right} containing the value for this instance.
*
* @since 1.1
*/
@Override
public Either<R, L> swap() { | return Right(value); |
pnerg/java-scala-util | src/main/java/javascalautils/Right.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
| import java.util.function.Function;
import static javascalautils.EitherCompanion.Left;
import java.io.Serializable; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the {@link Right} side of an {@link Either}.
*
* @author Peter Nerg
* @since 1.1
* @param <L> The type for the {@link Left} side (not used for this class)
* @param <R> The type for the {@link Right} side
*/
public final class Right<L, R> implements Either<L, R>, Serializable {
private static final long serialVersionUID = -2119790544433508346L;
private final R value;
/**
* Creates an instance wrapping the provide value.
*
* @param value The value wrapped by this instance
* @since 1.1
*/
public Right(R value) {
this.value = value;
}
/**
* Applies the provided <code>func_right</code> to the wrapped value and returns the result.
*
* @since 1.1
*/
@Override
public <T> T fold(Function<L, T> func_left, Function<R, T> func_right) {
return func_right.apply(value);
}
/**
* Always returns <code>true</code>.
*
* @since 1.1
*/
@Override
public boolean isRight() {
return true;
}
/**
* Returns a {@link Left} containing the value for this instance.
*
* @since 1.1
*/
@Override
public Either<R, L> swap() { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
// Path: src/main/java/javascalautils/Right.java
import java.util.function.Function;
import static javascalautils.EitherCompanion.Left;
import java.io.Serializable;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the {@link Right} side of an {@link Either}.
*
* @author Peter Nerg
* @since 1.1
* @param <L> The type for the {@link Left} side (not used for this class)
* @param <R> The type for the {@link Right} side
*/
public final class Right<L, R> implements Either<L, R>, Serializable {
private static final long serialVersionUID = -2119790544433508346L;
private final R value;
/**
* Creates an instance wrapping the provide value.
*
* @param value The value wrapped by this instance
* @since 1.1
*/
public Right(R value) {
this.value = value;
}
/**
* Applies the provided <code>func_right</code> to the wrapped value and returns the result.
*
* @since 1.1
*/
@Override
public <T> T fold(Function<L, T> func_left, Function<R, T> func_right) {
return func_right.apply(value);
}
/**
* Always returns <code>true</code>.
*
* @since 1.1
*/
@Override
public boolean isRight() {
return true;
}
/**
* Returns a {@link Left} containing the value for this instance.
*
* @since 1.1
*/
@Override
public Either<R, L> swap() { | return Left(value); |
pnerg/java-scala-util | src/test/java/javascalautils/TestTryCompanion.java | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
| import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link TryCompanion}
*
* @author Peter Nerg
*/
public class TestTryCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(TryCompanion.class);
}
@Test
public void try_withThrowableFunction0_success() throws Throwable { | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
// Path: src/test/java/javascalautils/TestTryCompanion.java
import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link TryCompanion}
*
* @author Peter Nerg
*/
public class TestTryCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(TryCompanion.class);
}
@Test
public void try_withThrowableFunction0_success() throws Throwable { | Try<Integer> t = Try(() -> 9 / 3); |
pnerg/java-scala-util | src/test/java/javascalautils/TestTryCompanion.java | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
| import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test; | public void try_withThrowableFunction0_failure() throws Throwable {
Try<Integer> t = Try(() -> 9 / 0);
assertTrue(t.isFailure());
}
@Test
public void try_withVoidFunction0_success() throws Throwable {
Try<Unit> t =
Try(
() -> {
String s = "does nothing";
s.length();
});
assertEquals(Unit.Instance, t.get());
}
@Test
public void try_withVoidFunction0_failure() throws Throwable {
Try<Unit> t =
Try(
() -> {
// pointless function, but has no return type and will fail here
@SuppressWarnings("unused")
int val = 9 / 0;
});
assertTrue(t.isFailure());
}
@Test
public void success() throws Throwable { | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
// Path: src/test/java/javascalautils/TestTryCompanion.java
import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test;
public void try_withThrowableFunction0_failure() throws Throwable {
Try<Integer> t = Try(() -> 9 / 0);
assertTrue(t.isFailure());
}
@Test
public void try_withVoidFunction0_success() throws Throwable {
Try<Unit> t =
Try(
() -> {
String s = "does nothing";
s.length();
});
assertEquals(Unit.Instance, t.get());
}
@Test
public void try_withVoidFunction0_failure() throws Throwable {
Try<Unit> t =
Try(
() -> {
// pointless function, but has no return type and will fail here
@SuppressWarnings("unused")
int val = 9 / 0;
});
assertTrue(t.isFailure());
}
@Test
public void success() throws Throwable { | Try<Integer> t = Success(69); |
pnerg/java-scala-util | src/test/java/javascalautils/TestTryCompanion.java | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
| import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test; | public void try_withVoidFunction0_success() throws Throwable {
Try<Unit> t =
Try(
() -> {
String s = "does nothing";
s.length();
});
assertEquals(Unit.Instance, t.get());
}
@Test
public void try_withVoidFunction0_failure() throws Throwable {
Try<Unit> t =
Try(
() -> {
// pointless function, but has no return type and will fail here
@SuppressWarnings("unused")
int val = 9 / 0;
});
assertTrue(t.isFailure());
}
@Test
public void success() throws Throwable {
Try<Integer> t = Success(69);
assertEquals(69, t.get().intValue());
}
@Test(expected = DummyException.class)
public void failure() throws Throwable { | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Failure<T> Failure(Throwable throwable) {
// return new Failure<>(throwable);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
//
// Path: src/main/java/javascalautils/TryCompanion.java
// public static Try<Unit> Try(VoidFunction0 function) {
// return Try.apply(
// () -> {
// function.apply();
// return Unit.Instance;
// });
// }
// Path: src/test/java/javascalautils/TestTryCompanion.java
import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
import org.junit.Test;
public void try_withVoidFunction0_success() throws Throwable {
Try<Unit> t =
Try(
() -> {
String s = "does nothing";
s.length();
});
assertEquals(Unit.Instance, t.get());
}
@Test
public void try_withVoidFunction0_failure() throws Throwable {
Try<Unit> t =
Try(
() -> {
// pointless function, but has no return type and will fail here
@SuppressWarnings("unused")
int val = 9 / 0;
});
assertTrue(t.isFailure());
}
@Test
public void success() throws Throwable {
Try<Integer> t = Success(69);
assertEquals(69, t.get().intValue());
}
@Test(expected = DummyException.class)
public void failure() throws Throwable { | Try<Integer> t = Failure(new DummyException()); |
pnerg/java-scala-util | src/test/java/javascalautils/TestOptionCompanion.java | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
| import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() { | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
// Path: src/test/java/javascalautils/TestOptionCompanion.java
import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() { | Option<String> option = Option("Life is full of options"); |
pnerg/java-scala-util | src/test/java/javascalautils/TestOptionCompanion.java | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
| import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() {
Option<String> option = Option("Life is full of options");
assertEquals("Life is full of options", option.get());
}
@Test
public void some() { | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
// Path: src/test/java/javascalautils/TestOptionCompanion.java
import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() {
Option<String> option = Option("Life is full of options");
assertEquals("Life is full of options", option.get());
}
@Test
public void some() { | Option<String> option = Some("Some is never none"); |
pnerg/java-scala-util | src/test/java/javascalautils/TestOptionCompanion.java | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
| import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() {
Option<String> option = Option("Life is full of options");
assertEquals("Life is full of options", option.get());
}
@Test
public void some() {
Option<String> option = Some("Some is never none");
assertEquals("Some is never none", option.get());
}
@Test
public void none() { | // Path: src/main/java/javascalautils/OptionCompanion.java
// @SuppressWarnings("unchecked")
// public static <T> None<T> None() {
// return Option.DEFAULT_NONE;
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Option<T> Option(T value) {
// return Option.apply(value);
// }
//
// Path: src/main/java/javascalautils/OptionCompanion.java
// public static <T> Some<T> Some(T value) {
// return new Some<>(value);
// }
// Path: src/test/java/javascalautils/TestOptionCompanion.java
import static javascalautils.OptionCompanion.None;
import static javascalautils.OptionCompanion.Option;
import static javascalautils.OptionCompanion.Some;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link OptionCompanion}.
*
* @author Peter Nerg
*/
public class TestOptionCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(OptionCompanion.class);
}
@Test
public void option() {
Option<String> option = Option("Life is full of options");
assertEquals("Life is full of options", option.get());
}
@Test
public void some() {
Option<String> option = Some("Some is never none");
assertEquals("Some is never none", option.get());
}
@Test
public void none() { | Option<String> option = None(); |
pnerg/java-scala-util | src/main/java/javascalautils/LeftProjection.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
| import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* This is a left-biased wrapper for an instance of {@link Either}.
*
* @author Peter Nerg
* @since 1.1
*/
public class LeftProjection<L, R> extends Projection<L> implements Iterable<L>, Serializable {
private static final long serialVersionUID = 4251047373391313192L;
private final Either<L, R> either;
/**
* Creates an instance of the projection.
*
* @param either The instance to wrap.
* @since 1.1
*/
LeftProjection(Either<L, R> either) {
this.either = either;
}
/**
* Returns <code>false</code> if {@link Right} or returns the result of applying the predicate to
* the {@link Left} value.
*
* @param predicate The predicate to apply
* @return If this is a {@link Left} and the predicate matches the value
* @since 1.1
*/
public boolean exists(Predicate<L> predicate) {
return either.isLeft() && predicate.test(orNull());
}
/**
* Returns the value if this is a {@link Left} else the value provided by the supplier.
*
* @param supplier The supplier
* @return The value
* @since 1.1
*/
@Override
public L getOrElse(Supplier<L> supplier) {
return either.fold(v -> v, v -> supplier.get());
}
/**
* Returns a {@link Some} wrapping the {@link Either} if it's a {@link Left} and the value of the
* {@link Left} matches the predicate, else {@link None} .
*
* @param predicate The predicate to apply
* @return The resulting Option of the filter operation
* @since 1.1
*/
public Option<Either<L, R>> filter(Predicate<L> predicate) {
return Option.apply(exists(predicate) ? either : null);
}
/**
* Returns <code>true</code> if {@link Right} or returns the result of applying the predicate to
* the {@link Left} value.
*
* @param predicate The predicate to apply
* @return If it is a match
* @since 1.1
*/
public boolean forAll(Predicate<L> predicate) {
return !either.isLeft() || predicate.test(orNull());
}
/**
* If this projection contains a {@link Left} then a new {@link Left} is returned containing the
* value from the original {@link Right} mapped via the provided function, else the contained
* Either is returned as is.
*
* @param <T> The type to return as the new {@link Left}
* @param function The function
* @return Mapped Either
* @since 1.1
*/
@SuppressWarnings("unchecked")
public <T> Either<T, R> map(Function<L, T> function) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
// Path: src/main/java/javascalautils/LeftProjection.java
import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* This is a left-biased wrapper for an instance of {@link Either}.
*
* @author Peter Nerg
* @since 1.1
*/
public class LeftProjection<L, R> extends Projection<L> implements Iterable<L>, Serializable {
private static final long serialVersionUID = 4251047373391313192L;
private final Either<L, R> either;
/**
* Creates an instance of the projection.
*
* @param either The instance to wrap.
* @since 1.1
*/
LeftProjection(Either<L, R> either) {
this.either = either;
}
/**
* Returns <code>false</code> if {@link Right} or returns the result of applying the predicate to
* the {@link Left} value.
*
* @param predicate The predicate to apply
* @return If this is a {@link Left} and the predicate matches the value
* @since 1.1
*/
public boolean exists(Predicate<L> predicate) {
return either.isLeft() && predicate.test(orNull());
}
/**
* Returns the value if this is a {@link Left} else the value provided by the supplier.
*
* @param supplier The supplier
* @return The value
* @since 1.1
*/
@Override
public L getOrElse(Supplier<L> supplier) {
return either.fold(v -> v, v -> supplier.get());
}
/**
* Returns a {@link Some} wrapping the {@link Either} if it's a {@link Left} and the value of the
* {@link Left} matches the predicate, else {@link None} .
*
* @param predicate The predicate to apply
* @return The resulting Option of the filter operation
* @since 1.1
*/
public Option<Either<L, R>> filter(Predicate<L> predicate) {
return Option.apply(exists(predicate) ? either : null);
}
/**
* Returns <code>true</code> if {@link Right} or returns the result of applying the predicate to
* the {@link Left} value.
*
* @param predicate The predicate to apply
* @return If it is a match
* @since 1.1
*/
public boolean forAll(Predicate<L> predicate) {
return !either.isLeft() || predicate.test(orNull());
}
/**
* If this projection contains a {@link Left} then a new {@link Left} is returned containing the
* value from the original {@link Right} mapped via the provided function, else the contained
* Either is returned as is.
*
* @param <T> The type to return as the new {@link Left}
* @param function The function
* @return Mapped Either
* @since 1.1
*/
@SuppressWarnings("unchecked")
public <T> Either<T, R> map(Function<L, T> function) { | return either.isLeft() ? Left(function.apply(get())) : (Either<T, R>) either; |
pnerg/java-scala-util | src/test/java/javascalautils/TestEitherCompanion.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link EitherCompanion}
*
* @author Peter Nerg
*/
public class TestEitherCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(EitherCompanion.class);
}
@Test
public void left() { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/test/java/javascalautils/TestEitherCompanion.java
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link EitherCompanion}
*
* @author Peter Nerg
*/
public class TestEitherCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(EitherCompanion.class);
}
@Test
public void left() { | Either<Integer, String> either = Left(69); |
pnerg/java-scala-util | src/test/java/javascalautils/TestEitherCompanion.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
import org.junit.Test; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link EitherCompanion}
*
* @author Peter Nerg
*/
public class TestEitherCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(EitherCompanion.class);
}
@Test
public void left() {
Either<Integer, String> either = Left(69);
assertTrue(either.isLeft());
}
@Test
public void right() { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/test/java/javascalautils/TestEitherCompanion.java
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
import org.junit.Test;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Test the class {@link EitherCompanion}
*
* @author Peter Nerg
*/
public class TestEitherCompanion extends BaseAssert {
@Test
public void createInstance() throws ReflectiveOperationException {
assertPrivateConstructor(EitherCompanion.class);
}
@Test
public void left() {
Either<Integer, String> either = Left(69);
assertTrue(either.isLeft());
}
@Test
public void right() { | Either<Integer, String> either = Right("Right is not Left"); |
pnerg/java-scala-util | src/main/java/javascalautils/Failure.java | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
| import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.TryCompanion.Success;
import java.io.Serializable; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the <i>failure</i> implementation of {@link Try}. <br>
* Acts as a carrier for the result/throwable of a unsuccessful computation. <br>
* For examples on usage refer to the documentation for {@link Try}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the exception represented by this instance
*/
public final class Failure<T> extends EmptyContainer<T> implements Try<T>, Serializable {
private static final long serialVersionUID = -3153874073796965428L;
private final Throwable throwable;
/**
* Creates a Failure for the provided Throwable. <br>
* Null values are <b>not</b> allowed since a 'failure' needs a reason.
*
* @param throwable The throwable
* @since 1.0
*/
public Failure(Throwable throwable) {
this.throwable = Validator.requireNonNull(throwable, "Null values are not allowed for Failure");
}
/**
* Always returns <code>false</code>.
*
* @since 1.0
*/
@Override
public boolean isSuccess() {
return false;
}
/**
* Always returns the value provided by the supplier. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns the value provided by the supplier. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public Try<T> orElse(Supplier<Try<T>> supplier) {
return supplier.get();
}
/**
* Always throws the {@link Throwable} this instance represents. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public T get() throws Throwable {
throw throwable;
}
/**
* Returns a {@link Success} with the {@link Throwable} this instance represents.
*
* @since 1.0
*/
@Override
public Try<Throwable> failed() { | // Path: src/main/java/javascalautils/TryCompanion.java
// public static <T> Success<T> Success(T value) {
// return new Success<>(value);
// }
// Path: src/main/java/javascalautils/Failure.java
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.TryCompanion.Success;
import java.io.Serializable;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents the <i>failure</i> implementation of {@link Try}. <br>
* Acts as a carrier for the result/throwable of a unsuccessful computation. <br>
* For examples on usage refer to the documentation for {@link Try}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the exception represented by this instance
*/
public final class Failure<T> extends EmptyContainer<T> implements Try<T>, Serializable {
private static final long serialVersionUID = -3153874073796965428L;
private final Throwable throwable;
/**
* Creates a Failure for the provided Throwable. <br>
* Null values are <b>not</b> allowed since a 'failure' needs a reason.
*
* @param throwable The throwable
* @since 1.0
*/
public Failure(Throwable throwable) {
this.throwable = Validator.requireNonNull(throwable, "Null values are not allowed for Failure");
}
/**
* Always returns <code>false</code>.
*
* @since 1.0
*/
@Override
public boolean isSuccess() {
return false;
}
/**
* Always returns the value provided by the supplier. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns the value provided by the supplier. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public Try<T> orElse(Supplier<Try<T>> supplier) {
return supplier.get();
}
/**
* Always throws the {@link Throwable} this instance represents. <br>
* As per definition this is a failure without any data to return.
*
* @since 1.0
*/
@Override
public T get() throws Throwable {
throw throwable;
}
/**
* Returns a {@link Success} with the {@link Throwable} this instance represents.
*
* @since 1.0
*/
@Override
public Try<Throwable> failed() { | return Success(throwable); |
pnerg/java-scala-util | src/main/java/javascalautils/None.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents an empty {@link Option}. <br>
* The {@link None} is a replacement for <code>null</code> values representing a non-existing value.
* <br>
* One can consider {@link None} as a collection of size 0. <br>
* Instances of None should not be created directly, rather use the factory methods provided on
* {@link Option}.
*
* <ul>
* <li>{@link Option#empty()}
* <li>{@link Option#None()}
* </ul>
*
* Since {@link None} anyways cannot represent a value it is preferable to use it as a singleton
* saving unnecessary instance creation. <br>
* For examples on usage refer to the documentation for {@link Option}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the value represented by this instance
*/
public final class None<T> extends EmptyContainer<T> implements Option<T>, Serializable {
private static final long serialVersionUID = -5169653193196761412L;
/**
* Always throws {@link NoSuchElementException} since None cannot per definition hold any value.
*
* @since 1.0
*/
@Override
public T get() {
throw new NoSuchElementException("None cannot hold values");
}
/**
* Always the value provided by the supplier.
*
* @since 1.0
*/
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns <code>false</code>. <br>
* I.e. the predicate is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
public boolean exists(Predicate<T> predicate) {
return false;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
@SuppressWarnings("unchecked")
public <R> Option<R> map(ThrowableFunction1<T, R> function) {
return (Option<R>) this;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.2
* @since 1.0
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
// uses the Map method as it anyways produces the same result
return map(null);
}
/**
* Always the value provided by the supplier.
*
* @return The value provided by the supplier
* @since 1.0
*/
public Option<T> orElse(Supplier<Option<T>> supplier) {
return supplier.get();
}
/**
* Returns a {@link Right} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/None.java
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents an empty {@link Option}. <br>
* The {@link None} is a replacement for <code>null</code> values representing a non-existing value.
* <br>
* One can consider {@link None} as a collection of size 0. <br>
* Instances of None should not be created directly, rather use the factory methods provided on
* {@link Option}.
*
* <ul>
* <li>{@link Option#empty()}
* <li>{@link Option#None()}
* </ul>
*
* Since {@link None} anyways cannot represent a value it is preferable to use it as a singleton
* saving unnecessary instance creation. <br>
* For examples on usage refer to the documentation for {@link Option}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the value represented by this instance
*/
public final class None<T> extends EmptyContainer<T> implements Option<T>, Serializable {
private static final long serialVersionUID = -5169653193196761412L;
/**
* Always throws {@link NoSuchElementException} since None cannot per definition hold any value.
*
* @since 1.0
*/
@Override
public T get() {
throw new NoSuchElementException("None cannot hold values");
}
/**
* Always the value provided by the supplier.
*
* @since 1.0
*/
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns <code>false</code>. <br>
* I.e. the predicate is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
public boolean exists(Predicate<T> predicate) {
return false;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
@SuppressWarnings("unchecked")
public <R> Option<R> map(ThrowableFunction1<T, R> function) {
return (Option<R>) this;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.2
* @since 1.0
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
// uses the Map method as it anyways produces the same result
return map(null);
}
/**
* Always the value provided by the supplier.
*
* @return The value provided by the supplier
* @since 1.0
*/
public Option<T> orElse(Supplier<Option<T>> supplier) {
return supplier.get();
}
/**
* Returns a {@link Right} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) { | return Right(right.get()); |
pnerg/java-scala-util | src/main/java/javascalautils/None.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents an empty {@link Option}. <br>
* The {@link None} is a replacement for <code>null</code> values representing a non-existing value.
* <br>
* One can consider {@link None} as a collection of size 0. <br>
* Instances of None should not be created directly, rather use the factory methods provided on
* {@link Option}.
*
* <ul>
* <li>{@link Option#empty()}
* <li>{@link Option#None()}
* </ul>
*
* Since {@link None} anyways cannot represent a value it is preferable to use it as a singleton
* saving unnecessary instance creation. <br>
* For examples on usage refer to the documentation for {@link Option}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the value represented by this instance
*/
public final class None<T> extends EmptyContainer<T> implements Option<T>, Serializable {
private static final long serialVersionUID = -5169653193196761412L;
/**
* Always throws {@link NoSuchElementException} since None cannot per definition hold any value.
*
* @since 1.0
*/
@Override
public T get() {
throw new NoSuchElementException("None cannot hold values");
}
/**
* Always the value provided by the supplier.
*
* @since 1.0
*/
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns <code>false</code>. <br>
* I.e. the predicate is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
public boolean exists(Predicate<T> predicate) {
return false;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
@SuppressWarnings("unchecked")
public <R> Option<R> map(ThrowableFunction1<T, R> function) {
return (Option<R>) this;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.2
* @since 1.0
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
// uses the Map method as it anyways produces the same result
return map(null);
}
/**
* Always the value provided by the supplier.
*
* @return The value provided by the supplier
* @since 1.0
*/
public Option<T> orElse(Supplier<Option<T>> supplier) {
return supplier.get();
}
/**
* Returns a {@link Right} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) {
return Right(right.get());
}
/**
* Returns a {@link Left} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <L> Either<L, T> toRight(Supplier<L> left) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Left<L, R> Left(L value) {
// return new Left<>(value);
// }
//
// Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/None.java
import java.io.Serializable;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Left;
import static javascalautils.EitherCompanion.Right;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* Represents an empty {@link Option}. <br>
* The {@link None} is a replacement for <code>null</code> values representing a non-existing value.
* <br>
* One can consider {@link None} as a collection of size 0. <br>
* Instances of None should not be created directly, rather use the factory methods provided on
* {@link Option}.
*
* <ul>
* <li>{@link Option#empty()}
* <li>{@link Option#None()}
* </ul>
*
* Since {@link None} anyways cannot represent a value it is preferable to use it as a singleton
* saving unnecessary instance creation. <br>
* For examples on usage refer to the documentation for {@link Option}.
*
* @author Peter Nerg
* @since 1.0
* @param <T> The type of the value represented by this instance
*/
public final class None<T> extends EmptyContainer<T> implements Option<T>, Serializable {
private static final long serialVersionUID = -5169653193196761412L;
/**
* Always throws {@link NoSuchElementException} since None cannot per definition hold any value.
*
* @since 1.0
*/
@Override
public T get() {
throw new NoSuchElementException("None cannot hold values");
}
/**
* Always the value provided by the supplier.
*
* @since 1.0
*/
public T getOrElse(Supplier<T> supplier) {
return supplier.get();
}
/**
* Always returns <code>false</code>. <br>
* I.e. the predicate is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
public boolean exists(Predicate<T> predicate) {
return false;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.0
*/
@SuppressWarnings("unchecked")
public <R> Option<R> map(ThrowableFunction1<T, R> function) {
return (Option<R>) this;
}
/**
* Always returns <code>this</code>. <br>
* I.e. the function is never used as {@link None} represents nothing/no value.
*
* @since 1.2
* @since 1.0
*/
@Override
public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
// uses the Map method as it anyways produces the same result
return map(null);
}
/**
* Always the value provided by the supplier.
*
* @return The value provided by the supplier
* @since 1.0
*/
public Option<T> orElse(Supplier<Option<T>> supplier) {
return supplier.get();
}
/**
* Returns a {@link Right} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <R> Either<T, R> toLeft(Supplier<R> right) {
return Right(right.get());
}
/**
* Returns a {@link Left} containing the value from the provided supplier.
*
* @since 1.4
* @since 1.0
*/
@Override
public <L> Either<L, T> toRight(Supplier<L> left) { | return Left(left.get()); |
pnerg/java-scala-util | src/main/java/javascalautils/RightProjection.java | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
| import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Right; | /**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* This is a right-biased wrapper for an instance of {@link Either}.
*
* @author Peter Nerg
* @since 1.1
*/
public class RightProjection<L, R> extends Projection<R> implements Serializable {
private static final long serialVersionUID = 4251047373391313192L;
private final Either<L, R> either;
/**
* Creates an instance of the projection.
*
* @param either The instance to wrap.
* @since 1.1
*/
RightProjection(Either<L, R> either) {
this.either = either;
}
/**
* Returns <code>false</code> if {@link Left} or returns the result of applying the predicate to
* the {@link Right} value.
*
* @param predicate The predicate to apply
* @return If this is a {@link Right} and the predicate matches the value
* @since 1.1
*/
public boolean exists(Predicate<R> predicate) {
return either.isRight() && predicate.test(orNull());
}
/**
* Returns the value if this is a {@link Right} else the value provided by the supplier.
*
* @param supplier The supplier
* @return The value
* @since 1.1
*/
@Override
public R getOrElse(Supplier<R> supplier) {
return either.fold(v -> supplier.get(), v -> v);
}
/**
* Returns a {@link Some} wrapping the {@link Either} if it's a {@link Right} and the value of the
* {@link Right} matches the predicate, else {@link None} .
*
* @param predicate The predicate to apply
* @return The resulting Option of the filter operation
* @since 1.1
*/
public Option<Either<L, R>> filter(Predicate<R> predicate) {
return Option.apply(exists(predicate) ? either : null);
}
/**
* Returns <code>true</code> if {@link Left} or returns the result of applying the predicate to
* the {@link Right} value.
*
* @param predicate The predicate to apply
* @return If it is a match
* @since 1.1
*/
public boolean forAll(Predicate<R> predicate) {
return !either.isRight() || predicate.test(orNull());
}
/**
* If this projection contains a {@link Right} then a new {@link Right} is returned containing the
* value from the original {@link Right} mapped via the provided function, else the contained
* Either is returned as is.
*
* @param <T> The type to return as the new {@link Right}
* @param function The function
* @return Mapped Either
* @since 1.1
*/
@SuppressWarnings("unchecked")
public <T> Either<L, T> map(Function<R, T> function) { | // Path: src/main/java/javascalautils/EitherCompanion.java
// public static <L, R> Right<L, R> Right(R value) {
// return new Right<>(value);
// }
// Path: src/main/java/javascalautils/RightProjection.java
import java.io.Serializable;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static javascalautils.EitherCompanion.Right;
/**
* Copyright 2015 Peter Nerg
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 javascalautils;
/**
* This is a right-biased wrapper for an instance of {@link Either}.
*
* @author Peter Nerg
* @since 1.1
*/
public class RightProjection<L, R> extends Projection<R> implements Serializable {
private static final long serialVersionUID = 4251047373391313192L;
private final Either<L, R> either;
/**
* Creates an instance of the projection.
*
* @param either The instance to wrap.
* @since 1.1
*/
RightProjection(Either<L, R> either) {
this.either = either;
}
/**
* Returns <code>false</code> if {@link Left} or returns the result of applying the predicate to
* the {@link Right} value.
*
* @param predicate The predicate to apply
* @return If this is a {@link Right} and the predicate matches the value
* @since 1.1
*/
public boolean exists(Predicate<R> predicate) {
return either.isRight() && predicate.test(orNull());
}
/**
* Returns the value if this is a {@link Right} else the value provided by the supplier.
*
* @param supplier The supplier
* @return The value
* @since 1.1
*/
@Override
public R getOrElse(Supplier<R> supplier) {
return either.fold(v -> supplier.get(), v -> v);
}
/**
* Returns a {@link Some} wrapping the {@link Either} if it's a {@link Right} and the value of the
* {@link Right} matches the predicate, else {@link None} .
*
* @param predicate The predicate to apply
* @return The resulting Option of the filter operation
* @since 1.1
*/
public Option<Either<L, R>> filter(Predicate<R> predicate) {
return Option.apply(exists(predicate) ? either : null);
}
/**
* Returns <code>true</code> if {@link Left} or returns the result of applying the predicate to
* the {@link Right} value.
*
* @param predicate The predicate to apply
* @return If it is a match
* @since 1.1
*/
public boolean forAll(Predicate<R> predicate) {
return !either.isRight() || predicate.test(orNull());
}
/**
* If this projection contains a {@link Right} then a new {@link Right} is returned containing the
* value from the original {@link Right} mapped via the provided function, else the contained
* Either is returned as is.
*
* @param <T> The type to return as the new {@link Right}
* @param function The function
* @return Mapped Either
* @since 1.1
*/
@SuppressWarnings("unchecked")
public <T> Either<L, T> map(Function<R, T> function) { | return either.isRight() ? Right(function.apply(get())) : (Either<L, T>) either; |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/SettingActivity.java | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
| import android.annotation.TargetApi;
import android.app.FragmentManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import com.cjj.mousepaint.utils.StatusBarCompat; | package com.cjj.mousepaint;
/**
* Created by Administrator on 2015/11/20.
*/
public class SettingActivity extends AppCompatActivity {
private SettingsFragment mSettingsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting); | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
// Path: app/src/main/java/com/cjj/mousepaint/SettingActivity.java
import android.annotation.TargetApi;
import android.app.FragmentManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import com.cjj.mousepaint.utils.StatusBarCompat;
package com.cjj.mousepaint;
/**
* Created by Administrator on 2015/11/20.
*/
public class SettingActivity extends AppCompatActivity {
private SettingsFragment mSettingsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting); | StatusBarCompat.compat(this, getResources().getColor(R.color.brownness)); |
android-cjj/MousePaint | http/src/main/java/com/cjj/http/BaseHttp.java | // Path: http/src/main/java/com/cjj/listener/CallbackListener.java
// public class CallbackListener<T> extends BaseListener<T>{
//
// @Override
// public void onError(Exception e) {
//
// }
//
// @Override
// public void onSuccess(T result) {
//
// }
//
// @Override
// public void onStringResult(String result) {
//
// }
//
// @Override
// public void onDownloadFinish(String path) {
//
// }
//
// @Override
// public void onDownloadProgress(int progress) {
//
// }
//
//
// }
//
// Path: http/src/main/java/com/cjj/util/GenericsUtils.java
// public class GenericsUtils {
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * The class to introspect
// * @return the first generic declaration, or <code>Object.class</code> if
// * cannot be determined
// */
// public static Class getSuperClassGenricType(Class clazz) {
// return getSuperClassGenricType(clazz, 0);
// }
//
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * clazz The class to introspect
// * @param index
// * the Index of the generic ddeclaration,start from 0.
// */
// public static Class getSuperClassGenricType(Class clazz, int index)
// throws IndexOutOfBoundsException {
//
// Type genType = clazz.getGenericSuperclass();
//
// if (!(genType instanceof ParameterizedType)) {
// return Object.class;
// }
//
// Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//
// if (index >= params.length || index < 0) {
// return Object.class;
// }
// if (!(params[index] instanceof Class)) {
// return Object.class;
// }
// return (Class) params[index];
// }
// }
| import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.listener.CallbackListener;
import com.cjj.util.GenericsUtils;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Set; | package com.cjj.http;
/**
* Created by cjj on 2015/8/25.
*/
public class BaseHttp<T>{
private static final String TAG = "CJJ-BaseHttp";
private Gson mGson;
private OkHttpClient mOkHttpClient;
private Handler mHandler;
private static BaseHttp mBaseHttp;
protected BaseHttp()
{
mGson = new Gson();
mOkHttpClient = new OkHttpClient();
mHandler = new Handler(Looper.getMainLooper());
//cookie enabled
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}
protected static BaseHttp getInstance()
{
if(mBaseHttp == null)
{
mBaseHttp = new BaseHttp();
}
return mBaseHttp;
}
| // Path: http/src/main/java/com/cjj/listener/CallbackListener.java
// public class CallbackListener<T> extends BaseListener<T>{
//
// @Override
// public void onError(Exception e) {
//
// }
//
// @Override
// public void onSuccess(T result) {
//
// }
//
// @Override
// public void onStringResult(String result) {
//
// }
//
// @Override
// public void onDownloadFinish(String path) {
//
// }
//
// @Override
// public void onDownloadProgress(int progress) {
//
// }
//
//
// }
//
// Path: http/src/main/java/com/cjj/util/GenericsUtils.java
// public class GenericsUtils {
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * The class to introspect
// * @return the first generic declaration, or <code>Object.class</code> if
// * cannot be determined
// */
// public static Class getSuperClassGenricType(Class clazz) {
// return getSuperClassGenricType(clazz, 0);
// }
//
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * clazz The class to introspect
// * @param index
// * the Index of the generic ddeclaration,start from 0.
// */
// public static Class getSuperClassGenricType(Class clazz, int index)
// throws IndexOutOfBoundsException {
//
// Type genType = clazz.getGenericSuperclass();
//
// if (!(genType instanceof ParameterizedType)) {
// return Object.class;
// }
//
// Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//
// if (index >= params.length || index < 0) {
// return Object.class;
// }
// if (!(params[index] instanceof Class)) {
// return Object.class;
// }
// return (Class) params[index];
// }
// }
// Path: http/src/main/java/com/cjj/http/BaseHttp.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.listener.CallbackListener;
import com.cjj.util.GenericsUtils;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Set;
package com.cjj.http;
/**
* Created by cjj on 2015/8/25.
*/
public class BaseHttp<T>{
private static final String TAG = "CJJ-BaseHttp";
private Gson mGson;
private OkHttpClient mOkHttpClient;
private Handler mHandler;
private static BaseHttp mBaseHttp;
protected BaseHttp()
{
mGson = new Gson();
mOkHttpClient = new OkHttpClient();
mHandler = new Handler(Looper.getMainLooper());
//cookie enabled
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}
protected static BaseHttp getInstance()
{
if(mBaseHttp == null)
{
mBaseHttp = new BaseHttp();
}
return mBaseHttp;
}
| protected void baseGet(String url,CallbackListener<T> listener) |
android-cjj/MousePaint | http/src/main/java/com/cjj/http/BaseHttp.java | // Path: http/src/main/java/com/cjj/listener/CallbackListener.java
// public class CallbackListener<T> extends BaseListener<T>{
//
// @Override
// public void onError(Exception e) {
//
// }
//
// @Override
// public void onSuccess(T result) {
//
// }
//
// @Override
// public void onStringResult(String result) {
//
// }
//
// @Override
// public void onDownloadFinish(String path) {
//
// }
//
// @Override
// public void onDownloadProgress(int progress) {
//
// }
//
//
// }
//
// Path: http/src/main/java/com/cjj/util/GenericsUtils.java
// public class GenericsUtils {
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * The class to introspect
// * @return the first generic declaration, or <code>Object.class</code> if
// * cannot be determined
// */
// public static Class getSuperClassGenricType(Class clazz) {
// return getSuperClassGenricType(clazz, 0);
// }
//
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * clazz The class to introspect
// * @param index
// * the Index of the generic ddeclaration,start from 0.
// */
// public static Class getSuperClassGenricType(Class clazz, int index)
// throws IndexOutOfBoundsException {
//
// Type genType = clazz.getGenericSuperclass();
//
// if (!(genType instanceof ParameterizedType)) {
// return Object.class;
// }
//
// Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//
// if (index >= params.length || index < 0) {
// return Object.class;
// }
// if (!(params[index] instanceof Class)) {
// return Object.class;
// }
// return (Class) params[index];
// }
// }
| import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.listener.CallbackListener;
import com.cjj.util.GenericsUtils;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Set; |
protected Request getBaseRequest(String url)
{
Request request = new Request.Builder().url(url).tag(url).build();
return request;
}
protected void doRequest(Request request, final CallbackListener<T> listener)
{
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
listener.onError(e);
}
});
}
@Override
public void onResponse(Response response) throws IOException {
final String result = response.body().string();
Log.i(TAG, "结果:" + result);
if(isListenerNotNull(listener)) listener.onStringResult(result);
mHandler.post(new Runnable() {
@Override
public void run() {
try { | // Path: http/src/main/java/com/cjj/listener/CallbackListener.java
// public class CallbackListener<T> extends BaseListener<T>{
//
// @Override
// public void onError(Exception e) {
//
// }
//
// @Override
// public void onSuccess(T result) {
//
// }
//
// @Override
// public void onStringResult(String result) {
//
// }
//
// @Override
// public void onDownloadFinish(String path) {
//
// }
//
// @Override
// public void onDownloadProgress(int progress) {
//
// }
//
//
// }
//
// Path: http/src/main/java/com/cjj/util/GenericsUtils.java
// public class GenericsUtils {
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * The class to introspect
// * @return the first generic declaration, or <code>Object.class</code> if
// * cannot be determined
// */
// public static Class getSuperClassGenricType(Class clazz) {
// return getSuperClassGenricType(clazz, 0);
// }
//
// /**
// * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
// * GenricManager<Book>
// *
// * @param clazz
// * clazz The class to introspect
// * @param index
// * the Index of the generic ddeclaration,start from 0.
// */
// public static Class getSuperClassGenricType(Class clazz, int index)
// throws IndexOutOfBoundsException {
//
// Type genType = clazz.getGenericSuperclass();
//
// if (!(genType instanceof ParameterizedType)) {
// return Object.class;
// }
//
// Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//
// if (index >= params.length || index < 0) {
// return Object.class;
// }
// if (!(params[index] instanceof Class)) {
// return Object.class;
// }
// return (Class) params[index];
// }
// }
// Path: http/src/main/java/com/cjj/http/BaseHttp.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.listener.CallbackListener;
import com.cjj.util.GenericsUtils;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.Set;
protected Request getBaseRequest(String url)
{
Request request = new Request.Builder().url(url).tag(url).build();
return request;
}
protected void doRequest(Request request, final CallbackListener<T> listener)
{
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
listener.onError(e);
}
});
}
@Override
public void onResponse(Response response) throws IOException {
final String result = response.body().string();
Log.i(TAG, "结果:" + result);
if(isListenerNotNull(listener)) listener.onStringResult(result);
mHandler.post(new Runnable() {
@Override
public void run() {
try { | Class<T> clazz = GenericsUtils.getSuperClassGenricType(listener.getClass()); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/adapter/CategoryDetialAdapter.java | // Path: app/src/main/java/com/cjj/mousepaint/utils/ViewHolderUtils.java
// public class ViewHolderUtils {
//
// private static final String ID = "id";
//
// /**
// * 利用反射机制实例化对象,主要运用在Adapter复用
// * @param mContext 上下文对象
// * @param convertView 复用的view <b>(Adapter getView 方法中的convertView)</b>
// * @param layoutId 实例化布局ID
// * @param cls ViewHolder <b>(你的实体类)</b>
// * @return 装载后的view <b>(直接返回给getView)</b>
// */
// public static View loadingConvertView(Context mContext,View convertView,int layoutId,Class<?> cls)
// {
// try
// {
// if (null == convertView)
// {
// convertView = LayoutInflater.from(mContext).inflate(layoutId,null);
// Object obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// //得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// //允许访问私有属性
// mField.setAccessible(true);
// //保存实例化后的资源
// mField.set(obj,convertView.findViewById(resourceId));
// }
// convertView.setTag(obj);
// }
// }
// catch(Exception ex)
// {
// ex.printStackTrace();
// }
// return convertView;
// }
//
// /**
// * 利用反射机制实例化对象
// * <br><b>可以在RecyclerView中使用,没有复用机制,因为RecyclerView自带了</b></br>
// * <b>itemView.getContext()不能为空</b>
// * @param itemView 需要被反射的view
// * @param cls 反射后得到类对象
// * @return
// */
// public static <T>T loadingViewHolder(View itemView,Class<T> cls)
// {
// Context mContext = itemView.getContext();
// Object obj = null;
//
// try
// {
// obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// // 得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// // 允许访问私有属性
// mField.setAccessible(true);
// // 保存实例化后的资源
// mField.set(obj,itemView.findViewById(resourceId));
// }
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// return (T)obj;
// }
//
// }
| import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.mousepaint.utils.ViewHolderUtils;
import java.util.ArrayList;
import java.util.List; | package com.cjj.mousepaint.adapter;
/**
* Created by Administrator on 2015/11/3.
*/
public class CategoryDetialAdapter extends BaseAdapter {
private Activity context;
private List<CategoryModel.ReturnEntity.ListEntity> list;
private ViewHolder mHolder;
private int selectIndex = 0;
public CategoryDetialAdapter(Activity context, List<CategoryModel.ReturnEntity.ListEntity> list) {
this.context = context;
this.list = list;
}
public void updateData(List<CategoryModel.ReturnEntity.ListEntity> list)
{
this.list = list;
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public CategoryModel.ReturnEntity.ListEntity getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
mHolder = new ViewHolder(); | // Path: app/src/main/java/com/cjj/mousepaint/utils/ViewHolderUtils.java
// public class ViewHolderUtils {
//
// private static final String ID = "id";
//
// /**
// * 利用反射机制实例化对象,主要运用在Adapter复用
// * @param mContext 上下文对象
// * @param convertView 复用的view <b>(Adapter getView 方法中的convertView)</b>
// * @param layoutId 实例化布局ID
// * @param cls ViewHolder <b>(你的实体类)</b>
// * @return 装载后的view <b>(直接返回给getView)</b>
// */
// public static View loadingConvertView(Context mContext,View convertView,int layoutId,Class<?> cls)
// {
// try
// {
// if (null == convertView)
// {
// convertView = LayoutInflater.from(mContext).inflate(layoutId,null);
// Object obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// //得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// //允许访问私有属性
// mField.setAccessible(true);
// //保存实例化后的资源
// mField.set(obj,convertView.findViewById(resourceId));
// }
// convertView.setTag(obj);
// }
// }
// catch(Exception ex)
// {
// ex.printStackTrace();
// }
// return convertView;
// }
//
// /**
// * 利用反射机制实例化对象
// * <br><b>可以在RecyclerView中使用,没有复用机制,因为RecyclerView自带了</b></br>
// * <b>itemView.getContext()不能为空</b>
// * @param itemView 需要被反射的view
// * @param cls 反射后得到类对象
// * @return
// */
// public static <T>T loadingViewHolder(View itemView,Class<T> cls)
// {
// Context mContext = itemView.getContext();
// Object obj = null;
//
// try
// {
// obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// // 得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// // 允许访问私有属性
// mField.setAccessible(true);
// // 保存实例化后的资源
// mField.set(obj,itemView.findViewById(resourceId));
// }
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// return (T)obj;
// }
//
// }
// Path: app/src/main/java/com/cjj/mousepaint/adapter/CategoryDetialAdapter.java
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.mousepaint.utils.ViewHolderUtils;
import java.util.ArrayList;
import java.util.List;
package com.cjj.mousepaint.adapter;
/**
* Created by Administrator on 2015/11/3.
*/
public class CategoryDetialAdapter extends BaseAdapter {
private Activity context;
private List<CategoryModel.ReturnEntity.ListEntity> list;
private ViewHolder mHolder;
private int selectIndex = 0;
public CategoryDetialAdapter(Activity context, List<CategoryModel.ReturnEntity.ListEntity> list) {
this.context = context;
this.list = list;
}
public void updateData(List<CategoryModel.ReturnEntity.ListEntity> list)
{
this.list = list;
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public CategoryModel.ReturnEntity.ListEntity getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
mHolder = new ViewHolder(); | convertView = ViewHolderUtils.loadingConvertView(parent.getContext(), convertView, R.layout.item_category_detial, ViewHolder.class); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/WebActivity.java | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
| import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.cjj.mousepaint.utils.StatusBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife; | package com.cjj.mousepaint;
public class WebActivity extends BaseActivity {
public static final String EXTRA_URL = "extra_url";
public static final String EXTRA_TITLE = "title";
@Bind(R.id.webView) WebView mWebView;
// @Bind(R.id.swipe_back) SwipebackLayout mSwipeBack;
Context mContext;
String mUrl, mTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
ButterKnife.bind(this); | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
// Path: app/src/main/java/com/cjj/mousepaint/WebActivity.java
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.cjj.mousepaint.utils.StatusBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife;
package com.cjj.mousepaint;
public class WebActivity extends BaseActivity {
public static final String EXTRA_URL = "extra_url";
public static final String EXTRA_TITLE = "title";
@Bind(R.id.webView) WebView mWebView;
// @Bind(R.id.swipe_back) SwipebackLayout mSwipeBack;
Context mContext;
String mUrl, mTitle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
ButterKnife.bind(this); | StatusBarCompat.compat(this, getResources().getColor(R.color.black_tran)); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/adapter/ViewPagerAdvAdapter.java | // Path: app/src/main/java/com/cjj/mousepaint/WebActivity.java
// public class WebActivity extends BaseActivity {
//
// public static final String EXTRA_URL = "extra_url";
// public static final String EXTRA_TITLE = "title";
//
// @Bind(R.id.webView) WebView mWebView;
// // @Bind(R.id.swipe_back) SwipebackLayout mSwipeBack;
//
// Context mContext;
// String mUrl, mTitle;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_web);
// ButterKnife.bind(this);
// StatusBarCompat.compat(this, getResources().getColor(R.color.black_tran));
// mContext = this;
// mUrl = getIntent().getStringExtra(EXTRA_URL);
// Log.i("url","url----->"+mUrl);
// mTitle = getIntent().getStringExtra(EXTRA_TITLE);
//
// WebSettings settings = mWebView.getSettings();
// settings.setJavaScriptEnabled(true);
// settings.setLoadWithOverviewMode(true);
// settings.setAppCacheEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// settings.setSupportZoom(true);
// mWebView.setWebChromeClient(new ChromeClient());
// mWebView.setWebViewClient(new MyWebClient());
//
// mWebView.loadUrl(mUrl);
//
// }
//
//
//
//
// @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (event.getAction() == KeyEvent.ACTION_DOWN) {
// switch (keyCode) {
// case KeyEvent.KEYCODE_BACK:
// if (mWebView.canGoBack()) {
// mWebView.goBack();
// }
// else {
// finish();
// }
// return true;
// }
// }
// return super.onKeyDown(keyCode, event);
// }
//
// @Override protected void onDestroy() {
// super.onDestroy();
// if (mWebView != null) mWebView.destroy();
// ButterKnife.unbind(this);
// }
//
// @Override protected void onPause() {
// if (mWebView != null) mWebView.onPause();
// super.onPause();
// }
//
// @Override protected void onResume() {
// super.onResume();
// if (mWebView != null) mWebView.onResume();
// }
//
// private class ChromeClient extends WebChromeClient {
//
// @Override public void onProgressChanged(WebView view, int newProgress) {
// super.onProgressChanged(view, newProgress);
// // mProgressbar.setProgress(newProgress);
// }
//
// @Override public void onReceivedTitle(WebView view, String title) {
// super.onReceivedTitle(view, title);
// setTitle(title);
// }
// }
//
// private class MyWebClient extends WebViewClient {
//
// public boolean shouldOverrideUrlLoading(WebView view, String url) {
// if (url != null) view.loadUrl(url);
// return true;
// }
// }
// }
//
// Path: app/src/main/java/com/cjj/mousepaint/model/AdvModel.java
// public class AdvModel {
//
// /**
// * Id : 1
// * title : 《海贼王》1-20卷日版封面,高清大图分享
// * Img : http://img02.ishuhui.com/guanggao/app3.jpg
// * Link : http://www.ishuhui.net/CMS/648
// */
//
// public List<ListEntity> list;
//
// public static class ListEntity {
// public int Id;
// public String title;
// public String Img;
// public String Link;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.WebActivity;
import com.cjj.mousepaint.model.AdvModel;
import java.util.ArrayList;
import java.util.List; | int length = mDatas == null ? 0 : mDatas.size();
Log.i("cjj","tagcjj1111");
for (int i = 0; i < length; i++) {
ImageView mImageView = new ImageView(mContext);
mViews.add(mImageView);
}
length = 0;
}
@Override
public int getCount() {
return mDatas == null ? 0 : mDatas.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (arg1);
}
@Override
public Object instantiateItem(View container, final int position) {
mImageView = mViews.get(position);
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { | // Path: app/src/main/java/com/cjj/mousepaint/WebActivity.java
// public class WebActivity extends BaseActivity {
//
// public static final String EXTRA_URL = "extra_url";
// public static final String EXTRA_TITLE = "title";
//
// @Bind(R.id.webView) WebView mWebView;
// // @Bind(R.id.swipe_back) SwipebackLayout mSwipeBack;
//
// Context mContext;
// String mUrl, mTitle;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_web);
// ButterKnife.bind(this);
// StatusBarCompat.compat(this, getResources().getColor(R.color.black_tran));
// mContext = this;
// mUrl = getIntent().getStringExtra(EXTRA_URL);
// Log.i("url","url----->"+mUrl);
// mTitle = getIntent().getStringExtra(EXTRA_TITLE);
//
// WebSettings settings = mWebView.getSettings();
// settings.setJavaScriptEnabled(true);
// settings.setLoadWithOverviewMode(true);
// settings.setAppCacheEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// settings.setSupportZoom(true);
// mWebView.setWebChromeClient(new ChromeClient());
// mWebView.setWebViewClient(new MyWebClient());
//
// mWebView.loadUrl(mUrl);
//
// }
//
//
//
//
// @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (event.getAction() == KeyEvent.ACTION_DOWN) {
// switch (keyCode) {
// case KeyEvent.KEYCODE_BACK:
// if (mWebView.canGoBack()) {
// mWebView.goBack();
// }
// else {
// finish();
// }
// return true;
// }
// }
// return super.onKeyDown(keyCode, event);
// }
//
// @Override protected void onDestroy() {
// super.onDestroy();
// if (mWebView != null) mWebView.destroy();
// ButterKnife.unbind(this);
// }
//
// @Override protected void onPause() {
// if (mWebView != null) mWebView.onPause();
// super.onPause();
// }
//
// @Override protected void onResume() {
// super.onResume();
// if (mWebView != null) mWebView.onResume();
// }
//
// private class ChromeClient extends WebChromeClient {
//
// @Override public void onProgressChanged(WebView view, int newProgress) {
// super.onProgressChanged(view, newProgress);
// // mProgressbar.setProgress(newProgress);
// }
//
// @Override public void onReceivedTitle(WebView view, String title) {
// super.onReceivedTitle(view, title);
// setTitle(title);
// }
// }
//
// private class MyWebClient extends WebViewClient {
//
// public boolean shouldOverrideUrlLoading(WebView view, String url) {
// if (url != null) view.loadUrl(url);
// return true;
// }
// }
// }
//
// Path: app/src/main/java/com/cjj/mousepaint/model/AdvModel.java
// public class AdvModel {
//
// /**
// * Id : 1
// * title : 《海贼王》1-20卷日版封面,高清大图分享
// * Img : http://img02.ishuhui.com/guanggao/app3.jpg
// * Link : http://www.ishuhui.net/CMS/648
// */
//
// public List<ListEntity> list;
//
// public static class ListEntity {
// public int Id;
// public String title;
// public String Img;
// public String Link;
// }
// }
// Path: app/src/main/java/com/cjj/mousepaint/adapter/ViewPagerAdvAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.WebActivity;
import com.cjj.mousepaint.model.AdvModel;
import java.util.ArrayList;
import java.util.List;
int length = mDatas == null ? 0 : mDatas.size();
Log.i("cjj","tagcjj1111");
for (int i = 0; i < length; i++) {
ImageView mImageView = new ImageView(mContext);
mViews.add(mImageView);
}
length = 0;
}
@Override
public int getCount() {
return mDatas == null ? 0 : mDatas.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == (arg1);
}
@Override
public Object instantiateItem(View container, final int position) {
mImageView = mViews.get(position);
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
mImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) { | Intent intent = new Intent(mContext, WebActivity.class); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/AboutActivity.java | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
| import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.cjj.mousepaint.utils.StatusBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife; | package com.cjj.mousepaint;
/**
* Created by Administrator on 2015/10/9.
*/
public class AboutActivity extends AppCompatActivity {
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(R.id.tv_version)
TextView mVersionTextView;
@Bind(R.id.collapsing_toolbar)
CollapsingToolbarLayout mCollapsingToolbarLayout;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ButterKnife.bind(this); | // Path: app/src/main/java/com/cjj/mousepaint/utils/StatusBarCompat.java
// public class StatusBarCompat
// {
// private static final int INVALID_VAL = -1;
// private static final int COLOR_DEFAULT = Color.parseColor("#20000000");
//
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public static void compat(Activity activity, int statusColor)
// {
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
// {
// // if (statusColor != INVALID_VAL)
// // {
// // activity.getWindow().setStatusBarColor(statusColor);
// // }
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
// {
// int color = COLOR_DEFAULT;
// ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// if (statusColor != INVALID_VAL)
// {
// color = statusColor;
// }
// View statusBarView = contentView.getChildAt(0);
// //改变颜色时避免重复添加statusBarView
// if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity))
// {
// statusBarView.setBackgroundColor(color);
// return;
// }
// statusBarView = new View(activity);
// ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
// getStatusBarHeight(activity));
// statusBarView.setBackgroundColor(color);
// contentView.addView(statusBarView, lp);
// }
//
// }
//
// public static void compat(Activity activity)
// {
// compat(activity, INVALID_VAL);
// }
//
//
// public static int getStatusBarHeight(Context context)
// {
// int result = 0;
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// if (resourceId > 0)
// {
// result = context.getResources().getDimensionPixelSize(resourceId);
// }
// return result;
// }
// }
// Path: app/src/main/java/com/cjj/mousepaint/AboutActivity.java
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.cjj.mousepaint.utils.StatusBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife;
package com.cjj.mousepaint;
/**
* Created by Administrator on 2015/10/9.
*/
public class AboutActivity extends AppCompatActivity {
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(R.id.tv_version)
TextView mVersionTextView;
@Bind(R.id.collapsing_toolbar)
CollapsingToolbarLayout mCollapsingToolbarLayout;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ButterKnife.bind(this); | StatusBarCompat.compat(this, getResources().getColor(R.color.brownness)); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/adapter/DetialBookAdapter.java | // Path: app/src/main/java/com/cjj/mousepaint/utils/ViewHolderUtils.java
// public class ViewHolderUtils {
//
// private static final String ID = "id";
//
// /**
// * 利用反射机制实例化对象,主要运用在Adapter复用
// * @param mContext 上下文对象
// * @param convertView 复用的view <b>(Adapter getView 方法中的convertView)</b>
// * @param layoutId 实例化布局ID
// * @param cls ViewHolder <b>(你的实体类)</b>
// * @return 装载后的view <b>(直接返回给getView)</b>
// */
// public static View loadingConvertView(Context mContext,View convertView,int layoutId,Class<?> cls)
// {
// try
// {
// if (null == convertView)
// {
// convertView = LayoutInflater.from(mContext).inflate(layoutId,null);
// Object obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// //得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// //允许访问私有属性
// mField.setAccessible(true);
// //保存实例化后的资源
// mField.set(obj,convertView.findViewById(resourceId));
// }
// convertView.setTag(obj);
// }
// }
// catch(Exception ex)
// {
// ex.printStackTrace();
// }
// return convertView;
// }
//
// /**
// * 利用反射机制实例化对象
// * <br><b>可以在RecyclerView中使用,没有复用机制,因为RecyclerView自带了</b></br>
// * <b>itemView.getContext()不能为空</b>
// * @param itemView 需要被反射的view
// * @param cls 反射后得到类对象
// * @return
// */
// public static <T>T loadingViewHolder(View itemView,Class<T> cls)
// {
// Context mContext = itemView.getContext();
// Object obj = null;
//
// try
// {
// obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// // 得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// // 允许访问私有属性
// mField.setAccessible(true);
// // 保存实例化后的资源
// mField.set(obj,itemView.findViewById(resourceId));
// }
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// return (T)obj;
// }
//
// }
| import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.mousepaint.model.DetialComicBookModel;
import com.cjj.mousepaint.utils.ViewHolderUtils;
import java.util.ArrayList;
import java.util.List; | package com.cjj.mousepaint.adapter;
/**
* Created by Administrator on 2015/11/3.
*/
public class DetialBookAdapter extends BaseAdapter {
private Activity context;
private List<DetialComicBookModel.ReturnEntity.ListEntity> list;
private ViewHolder mHolder;
private int selectIndex = 0;
public DetialBookAdapter(Activity context, List<DetialComicBookModel.ReturnEntity.ListEntity> list) {
this.context = context;
this.list = list;
}
public void updateData(List<DetialComicBookModel.ReturnEntity.ListEntity> list)
{
this.list = list;
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public DetialComicBookModel.ReturnEntity.ListEntity getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
mHolder = new ViewHolder(); | // Path: app/src/main/java/com/cjj/mousepaint/utils/ViewHolderUtils.java
// public class ViewHolderUtils {
//
// private static final String ID = "id";
//
// /**
// * 利用反射机制实例化对象,主要运用在Adapter复用
// * @param mContext 上下文对象
// * @param convertView 复用的view <b>(Adapter getView 方法中的convertView)</b>
// * @param layoutId 实例化布局ID
// * @param cls ViewHolder <b>(你的实体类)</b>
// * @return 装载后的view <b>(直接返回给getView)</b>
// */
// public static View loadingConvertView(Context mContext,View convertView,int layoutId,Class<?> cls)
// {
// try
// {
// if (null == convertView)
// {
// convertView = LayoutInflater.from(mContext).inflate(layoutId,null);
// Object obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// //得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// //允许访问私有属性
// mField.setAccessible(true);
// //保存实例化后的资源
// mField.set(obj,convertView.findViewById(resourceId));
// }
// convertView.setTag(obj);
// }
// }
// catch(Exception ex)
// {
// ex.printStackTrace();
// }
// return convertView;
// }
//
// /**
// * 利用反射机制实例化对象
// * <br><b>可以在RecyclerView中使用,没有复用机制,因为RecyclerView自带了</b></br>
// * <b>itemView.getContext()不能为空</b>
// * @param itemView 需要被反射的view
// * @param cls 反射后得到类对象
// * @return
// */
// public static <T>T loadingViewHolder(View itemView,Class<T> cls)
// {
// Context mContext = itemView.getContext();
// Object obj = null;
//
// try
// {
// obj = cls.newInstance();
// Field[] mFields = obj.getClass().getDeclaredFields();
//
// for (Field mField : mFields)
// {
// // 得到资源ID
// int resourceId = mContext.getResources().getIdentifier(mField.getName(),ID,mContext.getApplicationContext().getPackageName());
// // 允许访问私有属性
// mField.setAccessible(true);
// // 保存实例化后的资源
// mField.set(obj,itemView.findViewById(resourceId));
// }
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// return (T)obj;
// }
//
// }
// Path: app/src/main/java/com/cjj/mousepaint/adapter/DetialBookAdapter.java
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.CategoryModel;
import com.cjj.mousepaint.model.DetialComicBookModel;
import com.cjj.mousepaint.utils.ViewHolderUtils;
import java.util.ArrayList;
import java.util.List;
package com.cjj.mousepaint.adapter;
/**
* Created by Administrator on 2015/11/3.
*/
public class DetialBookAdapter extends BaseAdapter {
private Activity context;
private List<DetialComicBookModel.ReturnEntity.ListEntity> list;
private ViewHolder mHolder;
private int selectIndex = 0;
public DetialBookAdapter(Activity context, List<DetialComicBookModel.ReturnEntity.ListEntity> list) {
this.context = context;
this.list = list;
}
public void updateData(List<DetialComicBookModel.ReturnEntity.ListEntity> list)
{
this.list = list;
this.notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public DetialComicBookModel.ReturnEntity.ListEntity getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
mHolder = new ViewHolder(); | convertView = ViewHolderUtils.loadingConvertView(parent.getContext(), convertView, R.layout.item_detial_book, ViewHolder.class); |
android-cjj/MousePaint | app/src/main/java/com/cjj/mousepaint/contral/control/RhythmAdapter.java | // Path: app/src/main/java/com/cjj/mousepaint/model/Card.java
// public class Card implements Serializable {
// private static final long serialVersionUID = -5376313495678563362L;
//
// private String id;
//
// private int uid;
//
// private int upNum;
//
// private String title;
//
// private String backgroundColor;
//
// private String subTitle;
//
// private String digest;
//
// private String authorName;
//
// private String coverImgerUrl;
//
// private String iconUrl;
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public void setIconUrl(String iconUrl) {
// this.iconUrl = iconUrl;
// }
//
// public String getCoverImgerUrl() {
// return coverImgerUrl;
// }
//
// public void setCoverImgerUrl(String coverImgerUrl) {
// this.coverImgerUrl = coverImgerUrl;
// }
//
// public String getAuthorName() {
// return authorName;
// }
//
// public void setAuthorName(String authorName) {
// this.authorName = authorName;
// }
//
// public int getUpNum() {
// return upNum;
// }
//
// public void setUpNum(int upNum) {
// this.upNum = upNum;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public void setDigest(String digest) {
// this.digest = digest;
// }
//
// public String getSubTitle() {
// return subTitle;
// }
//
// public void setSubTitle(String subTitle) {
// this.subTitle = subTitle;
// }
//
// public String getBackgroundColor() {
// return backgroundColor;
// }
//
// public void setBackgroundColor(String backgroundColor) {
// this.backgroundColor = backgroundColor;
// }
//
// public int getUid() {
// return uid;
// }
//
// public void setUid(int uid) {
// this.uid = uid;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.Card;
import java.util.ArrayList;
import java.util.List; | package com.cjj.mousepaint.contral.control;
public class RhythmAdapter extends BaseAdapter {
private float itemWidth;
| // Path: app/src/main/java/com/cjj/mousepaint/model/Card.java
// public class Card implements Serializable {
// private static final long serialVersionUID = -5376313495678563362L;
//
// private String id;
//
// private int uid;
//
// private int upNum;
//
// private String title;
//
// private String backgroundColor;
//
// private String subTitle;
//
// private String digest;
//
// private String authorName;
//
// private String coverImgerUrl;
//
// private String iconUrl;
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public void setIconUrl(String iconUrl) {
// this.iconUrl = iconUrl;
// }
//
// public String getCoverImgerUrl() {
// return coverImgerUrl;
// }
//
// public void setCoverImgerUrl(String coverImgerUrl) {
// this.coverImgerUrl = coverImgerUrl;
// }
//
// public String getAuthorName() {
// return authorName;
// }
//
// public void setAuthorName(String authorName) {
// this.authorName = authorName;
// }
//
// public int getUpNum() {
// return upNum;
// }
//
// public void setUpNum(int upNum) {
// this.upNum = upNum;
// }
//
// public String getDigest() {
// return digest;
// }
//
// public void setDigest(String digest) {
// this.digest = digest;
// }
//
// public String getSubTitle() {
// return subTitle;
// }
//
// public void setSubTitle(String subTitle) {
// this.subTitle = subTitle;
// }
//
// public String getBackgroundColor() {
// return backgroundColor;
// }
//
// public void setBackgroundColor(String backgroundColor) {
// this.backgroundColor = backgroundColor;
// }
//
// public int getUid() {
// return uid;
// }
//
// public void setUid(int uid) {
// this.uid = uid;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
// }
// Path: app/src/main/java/com/cjj/mousepaint/contral/control/RhythmAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import com.cjj.mousepaint.R;
import com.cjj.mousepaint.model.Card;
import java.util.ArrayList;
import java.util.List;
package com.cjj.mousepaint.contral.control;
public class RhythmAdapter extends BaseAdapter {
private float itemWidth;
| private List<Card> mCardList; |
CellarHQ/cellarhq.com | model/src/main/generated/com/cellarhq/generated/tables/records/DatabasechangeloglockRecord.java | // Path: model/src/main/generated/com/cellarhq/generated/tables/Databasechangeloglock.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.12.3"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Databasechangeloglock extends TableImpl<DatabasechangeloglockRecord> {
//
// private static final long serialVersionUID = -413880592;
//
// /**
// * The reference instance of <code>public.databasechangeloglock</code>
// */
// public static final Databasechangeloglock DATABASECHANGELOGLOCK = new Databasechangeloglock();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<DatabasechangeloglockRecord> getRecordType() {
// return DatabasechangeloglockRecord.class;
// }
//
// /**
// * The column <code>public.databasechangeloglock.id</code>.
// */
// public final TableField<DatabasechangeloglockRecord, Integer> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.databasechangeloglock.locked</code>.
// */
// public final TableField<DatabasechangeloglockRecord, Boolean> LOCKED = createField(DSL.name("locked"), org.jooq.impl.SQLDataType.BOOLEAN.nullable(false), this, "");
//
// /**
// * The column <code>public.databasechangeloglock.lockgranted</code>.
// */
// public final TableField<DatabasechangeloglockRecord, LocalDateTime> LOCKGRANTED = createField(DSL.name("lockgranted"), org.jooq.impl.SQLDataType.LOCALDATETIME, this, "");
//
// /**
// * The column <code>public.databasechangeloglock.lockedby</code>.
// */
// public final TableField<DatabasechangeloglockRecord, String> LOCKEDBY = createField(DSL.name("lockedby"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
//
// /**
// * Create a <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock() {
// this(DSL.name("databasechangeloglock"), null);
// }
//
// /**
// * Create an aliased <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock(String alias) {
// this(DSL.name(alias), DATABASECHANGELOGLOCK);
// }
//
// /**
// * Create an aliased <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock(Name alias) {
// this(alias, DATABASECHANGELOGLOCK);
// }
//
// private Databasechangeloglock(Name alias, Table<DatabasechangeloglockRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Databasechangeloglock(Name alias, Table<DatabasechangeloglockRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, DSL.comment(""));
// }
//
// public <O extends Record> Databasechangeloglock(Table<O> child, ForeignKey<O, DatabasechangeloglockRecord> key) {
// super(child, key, DATABASECHANGELOGLOCK);
// }
//
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// @Override
// public List<Index> getIndexes() {
// return Arrays.<Index>asList(Indexes.DATABASECHANGELOGLOCK_PKEY);
// }
//
// @Override
// public UniqueKey<DatabasechangeloglockRecord> getPrimaryKey() {
// return Keys.DATABASECHANGELOGLOCK_PKEY;
// }
//
// @Override
// public List<UniqueKey<DatabasechangeloglockRecord>> getKeys() {
// return Arrays.<UniqueKey<DatabasechangeloglockRecord>>asList(Keys.DATABASECHANGELOGLOCK_PKEY);
// }
//
// @Override
// public Databasechangeloglock as(String alias) {
// return new Databasechangeloglock(DSL.name(alias), this);
// }
//
// @Override
// public Databasechangeloglock as(Name alias) {
// return new Databasechangeloglock(alias, this);
// }
//
// /**
// * Rename this table
// */
// @Override
// public Databasechangeloglock rename(String name) {
// return new Databasechangeloglock(DSL.name(name), null);
// }
//
// /**
// * Rename this table
// */
// @Override
// public Databasechangeloglock rename(Name name) {
// return new Databasechangeloglock(name, null);
// }
//
// // -------------------------------------------------------------------------
// // Row4 type methods
// // -------------------------------------------------------------------------
//
// @Override
// public Row4<Integer, Boolean, LocalDateTime, String> fieldsRow() {
// return (Row4) super.fieldsRow();
// }
// }
| import com.cellarhq.generated.tables.Databasechangeloglock;
import java.time.LocalDateTime;
import javax.annotation.processing.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record4;
import org.jooq.Row4;
import org.jooq.impl.UpdatableRecordImpl; | @Column(name = "lockedby", length = 255)
public String getLockedby() {
return (String) get(3);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
@Override
public Row4<Integer, Boolean, LocalDateTime, String> fieldsRow() {
return (Row4) super.fieldsRow();
}
@Override
public Row4<Integer, Boolean, LocalDateTime, String> valuesRow() {
return (Row4) super.valuesRow();
}
@Override
public Field<Integer> field1() { | // Path: model/src/main/generated/com/cellarhq/generated/tables/Databasechangeloglock.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.12.3"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Databasechangeloglock extends TableImpl<DatabasechangeloglockRecord> {
//
// private static final long serialVersionUID = -413880592;
//
// /**
// * The reference instance of <code>public.databasechangeloglock</code>
// */
// public static final Databasechangeloglock DATABASECHANGELOGLOCK = new Databasechangeloglock();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<DatabasechangeloglockRecord> getRecordType() {
// return DatabasechangeloglockRecord.class;
// }
//
// /**
// * The column <code>public.databasechangeloglock.id</code>.
// */
// public final TableField<DatabasechangeloglockRecord, Integer> ID = createField(DSL.name("id"), org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.databasechangeloglock.locked</code>.
// */
// public final TableField<DatabasechangeloglockRecord, Boolean> LOCKED = createField(DSL.name("locked"), org.jooq.impl.SQLDataType.BOOLEAN.nullable(false), this, "");
//
// /**
// * The column <code>public.databasechangeloglock.lockgranted</code>.
// */
// public final TableField<DatabasechangeloglockRecord, LocalDateTime> LOCKGRANTED = createField(DSL.name("lockgranted"), org.jooq.impl.SQLDataType.LOCALDATETIME, this, "");
//
// /**
// * The column <code>public.databasechangeloglock.lockedby</code>.
// */
// public final TableField<DatabasechangeloglockRecord, String> LOCKEDBY = createField(DSL.name("lockedby"), org.jooq.impl.SQLDataType.VARCHAR(255), this, "");
//
// /**
// * Create a <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock() {
// this(DSL.name("databasechangeloglock"), null);
// }
//
// /**
// * Create an aliased <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock(String alias) {
// this(DSL.name(alias), DATABASECHANGELOGLOCK);
// }
//
// /**
// * Create an aliased <code>public.databasechangeloglock</code> table reference
// */
// public Databasechangeloglock(Name alias) {
// this(alias, DATABASECHANGELOGLOCK);
// }
//
// private Databasechangeloglock(Name alias, Table<DatabasechangeloglockRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Databasechangeloglock(Name alias, Table<DatabasechangeloglockRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, DSL.comment(""));
// }
//
// public <O extends Record> Databasechangeloglock(Table<O> child, ForeignKey<O, DatabasechangeloglockRecord> key) {
// super(child, key, DATABASECHANGELOGLOCK);
// }
//
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// @Override
// public List<Index> getIndexes() {
// return Arrays.<Index>asList(Indexes.DATABASECHANGELOGLOCK_PKEY);
// }
//
// @Override
// public UniqueKey<DatabasechangeloglockRecord> getPrimaryKey() {
// return Keys.DATABASECHANGELOGLOCK_PKEY;
// }
//
// @Override
// public List<UniqueKey<DatabasechangeloglockRecord>> getKeys() {
// return Arrays.<UniqueKey<DatabasechangeloglockRecord>>asList(Keys.DATABASECHANGELOGLOCK_PKEY);
// }
//
// @Override
// public Databasechangeloglock as(String alias) {
// return new Databasechangeloglock(DSL.name(alias), this);
// }
//
// @Override
// public Databasechangeloglock as(Name alias) {
// return new Databasechangeloglock(alias, this);
// }
//
// /**
// * Rename this table
// */
// @Override
// public Databasechangeloglock rename(String name) {
// return new Databasechangeloglock(DSL.name(name), null);
// }
//
// /**
// * Rename this table
// */
// @Override
// public Databasechangeloglock rename(Name name) {
// return new Databasechangeloglock(name, null);
// }
//
// // -------------------------------------------------------------------------
// // Row4 type methods
// // -------------------------------------------------------------------------
//
// @Override
// public Row4<Integer, Boolean, LocalDateTime, String> fieldsRow() {
// return (Row4) super.fieldsRow();
// }
// }
// Path: model/src/main/generated/com/cellarhq/generated/tables/records/DatabasechangeloglockRecord.java
import com.cellarhq.generated.tables.Databasechangeloglock;
import java.time.LocalDateTime;
import javax.annotation.processing.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record4;
import org.jooq.Row4;
import org.jooq.impl.UpdatableRecordImpl;
@Column(name = "lockedby", length = 255)
public String getLockedby() {
return (String) get(3);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
@Override
public Row4<Integer, Boolean, LocalDateTime, String> fieldsRow() {
return (Row4) super.fieldsRow();
}
@Override
public Row4<Integer, Boolean, LocalDateTime, String> valuesRow() {
return (Row4) super.valuesRow();
}
@Override
public Field<Integer> field1() { | return Databasechangeloglock.DATABASECHANGELOGLOCK.ID; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Aircraft.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("aircraft")
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@EqualsAndHashCode(of = {"attack", "health", "sheetName"}, callSuper = false)
public class Aircraft extends Unit implements Image {
private String ownerId; // id of the player which owns this item
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Aircraft.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("aircraft")
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@EqualsAndHashCode(of = {"attack", "health", "sheetName"}, callSuper = false)
public class Aircraft extends Unit implements Image {
private String ownerId; // id of the player which owns this item
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/email/SendEmail.java | // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
| import com.google.common.base.Strings;
import com.sendgrid.SendGrid;
import com.sendgrid.SendGridException;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Player; |
try {
SendGrid.Response response = sendgrid.send(email);
return response.getStatus();
} catch (SendGridException e) {
log.error("Error sending email: " + e.getMessage(), e);
}
return false;
}
public static boolean sendMessage(String email, String subject, String message, String playerId) {
if (System.getenv(SENDGRID_USERNAME) == null || System.getenv(SENDGRID_PASSWORD) == null) {
log.error("Missing environment variable for SENDGRID_USERNAME or SENDGRID_PASSWORD");
return false;
}
SendGrid.Email sendGridEmail = new SendGrid.Email();
sendGridEmail.addTo(email);
sendGridEmail.setFrom(NOREPLY_PLAYCIV_COM);
sendGridEmail.setSubject(subject);
sendGridEmail.setText(message + UNSUBSCRIBE(playerId));
try {
SendGrid.Response response = sendgrid.send(sendGridEmail);
return response.getStatus();
} catch (SendGridException e) {
log.error("Error sending sendGridEmail: " + e.getMessage(), e);
}
return false;
}
| // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/email/SendEmail.java
import com.google.common.base.Strings;
import com.sendgrid.SendGrid;
import com.sendgrid.SendGridException;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Player;
try {
SendGrid.Response response = sendgrid.send(email);
return response.getStatus();
} catch (SendGridException e) {
log.error("Error sending email: " + e.getMessage(), e);
}
return false;
}
public static boolean sendMessage(String email, String subject, String message, String playerId) {
if (System.getenv(SENDGRID_USERNAME) == null || System.getenv(SENDGRID_PASSWORD) == null) {
log.error("Missing environment variable for SENDGRID_USERNAME or SENDGRID_PASSWORD");
return false;
}
SendGrid.Email sendGridEmail = new SendGrid.Email();
sendGridEmail.addTo(email);
sendGridEmail.setFrom(NOREPLY_PLAYCIV_COM);
sendGridEmail.setSubject(subject);
sendGridEmail.setText(message + UNSUBSCRIBE(playerId));
try {
SendGrid.Response response = sendgrid.send(sendGridEmail);
return response.getStatus();
} catch (SendGridException e) {
log.error("Error sending sendGridEmail: " + e.getMessage(), e);
}
return false;
}
| public static boolean someoneJoinedTournament(Player player) { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Artillery.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("artillery")
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
public class Artillery extends Unit implements Image {
private int level = 0;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Artillery.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("artillery")
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
public class Artillery extends Unit implements Image {
private int level = 0;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/jackson/TurnKeyDeserializer.java | // Path: src/main/java/no/asgari/civilization/server/model/TurnKey.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class TurnKey implements Comparable<TurnKey> {
// private final int turnNumber;
// private final String username;
//
// public TurnKey(int turnNumber, String username) {
// this.turnNumber = turnNumber;
// this.username = username;
// }
//
// @Override
// public int compareTo(TurnKey o) {
// int v = Integer.valueOf(turnNumber).compareTo(o.getTurnNumber());
// if (v != 0) {
// return v;
// }
// return username.compareTo(o.getUsername());
// }
//
// @Override
// public String toString() {
// return "{" +
// "turnNumber:" + turnNumber +
// ", username:'" + username + "'" +
// "}";
// }
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import no.asgari.civilization.server.model.TurnKey;
import java.io.IOException; | package no.asgari.civilization.server.jackson;
public class TurnKeyDeserializer extends KeyDeserializer {
private static final ObjectMapper mapper = new ObjectMapper();
@Override | // Path: src/main/java/no/asgari/civilization/server/model/TurnKey.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// public class TurnKey implements Comparable<TurnKey> {
// private final int turnNumber;
// private final String username;
//
// public TurnKey(int turnNumber, String username) {
// this.turnNumber = turnNumber;
// this.username = username;
// }
//
// @Override
// public int compareTo(TurnKey o) {
// int v = Integer.valueOf(turnNumber).compareTo(o.getTurnNumber());
// if (v != 0) {
// return v;
// }
// return username.compareTo(o.getUsername());
// }
//
// @Override
// public String toString() {
// return "{" +
// "turnNumber:" + turnNumber +
// ", username:'" + username + "'" +
// "}";
// }
// }
// Path: src/main/java/no/asgari/civilization/server/jackson/TurnKeyDeserializer.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import no.asgari.civilization.server.model.TurnKey;
import java.io.IOException;
package no.asgari.civilization.server.jackson;
public class TurnKeyDeserializer extends KeyDeserializer {
private static final ObjectMapper mapper = new ObjectMapper();
@Override | public TurnKey deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/resource/TournamentResource.java | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
| import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List; | package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource { | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
// Path: src/main/java/no/asgari/civilization/server/resource/TournamentResource.java
import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource { | private final TournamentAction tournamentAction; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/resource/TournamentResource.java | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
| import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List; | package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource {
private final TournamentAction tournamentAction;
public TournamentResource(DB db) {
this.tournamentAction = new TournamentAction(db);
}
@Path("/signup/{tournamentNumber}")
@PUT | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
// Path: src/main/java/no/asgari/civilization/server/resource/TournamentResource.java
import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource {
private final TournamentAction tournamentAction;
public TournamentResource(DB db) {
this.tournamentAction = new TournamentAction(db);
}
@Path("/signup/{tournamentNumber}")
@PUT | public Response signup(@Auth Player player, @PathParam("tournamentNumber") int tournamentNumber) { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/resource/TournamentResource.java | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
| import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List; | package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource {
private final TournamentAction tournamentAction;
public TournamentResource(DB db) {
this.tournamentAction = new TournamentAction(db);
}
@Path("/signup/{tournamentNumber}")
@PUT
public Response signup(@Auth Player player, @PathParam("tournamentNumber") int tournamentNumber) {
boolean signedup = tournamentAction.signup(player, tournamentNumber);
if (signedup)
return Response.ok().entity(getTournaments()).build();
else return Response.status(Response.Status.BAD_REQUEST).build();
}
@GET | // Path: src/main/java/no/asgari/civilization/server/action/TournamentAction.java
// public class TournamentAction extends BaseAction {
// private final JacksonDBCollection<Player, String> playerCollection;
// private final JacksonDBCollection<Tournament, String> tournamentCol;
//
// public TournamentAction(DB db) {
// super(db);
// this.playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
// this.tournamentCol = JacksonDBCollection.wrap(db.getCollection(Tournament.COL_NAME), Tournament.class, String.class);
//
// }
//
// public boolean signup(Player player, int tournamentNumber) {
// List<Tournament> tournaments = tournamentCol.find().toArray();
// if (tournaments == null || tournaments.isEmpty()) {
// Tournament tournament = createTournament(tournamentNumber);
// tournament.getPlayers().add(new TournamentPlayer(player));
// return SendEmail.someoneJoinedTournament(player);
// }
//
// Tournament tournament = tournaments.get(tournamentNumber - 1);
// if (tournament.getPlayers().contains(new TournamentPlayer(player))) {
// return false;
// }
//
// tournament.getPlayers().add(new TournamentPlayer(player));
// tournamentCol.save(tournament);
//
// return SendEmail.someoneJoinedTournament(player);
// }
//
// private Tournament createTournament(int nr) {
// Tournament t = new Tournament();
// t.setName("First tournament");
// t.setTournamentNumber(nr);
// tournamentCol.save(t);
// return t;
// }
//
// public List<Tournament> getTournaments() {
// return tournamentCol.find().toArray();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/tournament/Tournament.java
// @Data
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Tournament {
// public static final String COL_NAME = "tournament";
//
// @ObjectId
// @Id
// private String id;
//
// private String name;
// private int tournamentNumber;
// private List<TournamentPlayer> players = new ArrayList<>();
// }
// Path: src/main/java/no/asgari/civilization/server/resource/TournamentResource.java
import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.TournamentAction;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.tournament.Tournament;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
package no.asgari.civilization.server.resource;
@Path("tournament")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TournamentResource {
private final TournamentAction tournamentAction;
public TournamentResource(DB db) {
this.tournamentAction = new TournamentAction(db);
}
@Path("/signup/{tournamentNumber}")
@PUT
public Response signup(@Auth Player player, @PathParam("tournamentNumber") int tournamentNumber) {
boolean signedup = tournamentAction.signup(player, tournamentNumber);
if (signedup)
return Response.ok().entity(getTournaments()).build();
else return Response.status(Response.Status.BAD_REQUEST).build();
}
@GET | public List<Tournament> getTournaments() { |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/resource/AdminResourceTest.java | // Path: src/main/java/no/asgari/civilization/server/model/PBF.java
// @Data
// @JsonRootName(value = "pbf")
// @XmlRootElement
// @JsonInclude
// @JsonIgnoreProperties(ignoreUnknown = true)
// //Perhaps use this when the object keep getting changed, otherwise jackson throws exception when it cannot map
// public class PBF {
// @JsonIgnore
// public static final String COL_NAME = "pbf";
// @JsonIgnore
// public static final String NAME = "name";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// private String name;
// private GameType type;
// private String mapLink;
// private String assetLink;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// private int numOfPlayers;
// private boolean active = true;
// private String winner; //username
// private List<Item> items = Lists.newArrayList();
// private List<Playerhand> players = Lists.newArrayList();
// private List<Tech> techs = Lists.newArrayList();
// private List<SocialPolicy> socialPolicies = new ArrayList<>(8);
//
// //@JsonSerialize(keyUsing=TurnKeySerializer.class)
// //@JsonDeserialize(keyUsing = TurnKeyDeserializer.class)
// private Map<String, PlayerTurn> publicTurns = new HashMap<>();
//
// //Will use these to reshuffle items which are discarded and can be drawn again
// private List<Item> discardedItems = new ArrayList<>();
//
// //If a player leaves, his items and stuff will be put here
// private List<Playerhand> withdrawnPlayers = new ArrayList<>();
//
// private boolean tournament = false;
//
// /**
// * Returns the username of the player who is start of turn
// */
// @JsonIgnore
// public String getNameOfUsersTurn() {
// Optional<Playerhand> optional = players.stream()
// .filter(Playerhand::isYourTurn)
// .findFirst();
//
// if (optional.isPresent()) {
// return optional.get().getUsername();
// }
//
// return "";
// }
//
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
| import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import static org.assertj.core.api.Assertions.assertThat; | package no.asgari.civilization.server.resource;
public class AdminResourceTest extends AbstractCivilizationTest {
protected static String BASE_URL = String.format("http://localhost:%d/api", RULE.getLocalPort());
@Test
public void adminCanChangeUser() { | // Path: src/main/java/no/asgari/civilization/server/model/PBF.java
// @Data
// @JsonRootName(value = "pbf")
// @XmlRootElement
// @JsonInclude
// @JsonIgnoreProperties(ignoreUnknown = true)
// //Perhaps use this when the object keep getting changed, otherwise jackson throws exception when it cannot map
// public class PBF {
// @JsonIgnore
// public static final String COL_NAME = "pbf";
// @JsonIgnore
// public static final String NAME = "name";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// private String name;
// private GameType type;
// private String mapLink;
// private String assetLink;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// private int numOfPlayers;
// private boolean active = true;
// private String winner; //username
// private List<Item> items = Lists.newArrayList();
// private List<Playerhand> players = Lists.newArrayList();
// private List<Tech> techs = Lists.newArrayList();
// private List<SocialPolicy> socialPolicies = new ArrayList<>(8);
//
// //@JsonSerialize(keyUsing=TurnKeySerializer.class)
// //@JsonDeserialize(keyUsing = TurnKeyDeserializer.class)
// private Map<String, PlayerTurn> publicTurns = new HashMap<>();
//
// //Will use these to reshuffle items which are discarded and can be drawn again
// private List<Item> discardedItems = new ArrayList<>();
//
// //If a player leaves, his items and stuff will be put here
// private List<Playerhand> withdrawnPlayers = new ArrayList<>();
//
// private boolean tournament = false;
//
// /**
// * Returns the username of the player who is start of turn
// */
// @JsonIgnore
// public String getNameOfUsersTurn() {
// Optional<Playerhand> optional = players.stream()
// .filter(Playerhand::isYourTurn)
// .findFirst();
//
// if (optional.isPresent()) {
// return optional.get().getUsername();
// }
//
// return "";
// }
//
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
// Path: src/test/java/no/asgari/civilization/server/resource/AdminResourceTest.java
import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import static org.assertj.core.api.Assertions.assertThat;
package no.asgari.civilization.server.resource;
public class AdminResourceTest extends AbstractCivilizationTest {
protected static String BASE_URL = String.format("http://localhost:%d/api", RULE.getLocalPort());
@Test
public void adminCanChangeUser() { | PBF pbf = getApp().pbfCollection.findOne(); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/CreateNewGameDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
| import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@Data
@JsonRootName(value = "createNewGame")
public class CreateNewGameDTO {
@NotEmpty
public String name;
@NotNull | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
// Path: src/main/java/no/asgari/civilization/server/dto/CreateNewGameDTO.java
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@Data
@JsonRootName(value = "createNewGame")
public class CreateNewGameDTO {
@NotEmpty
public String name;
@NotNull | private GameType type; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Wonder.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString()
@JsonTypeName("wonder")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Wonder implements Item {
@JsonIgnore
public static final String ANCIENT = "Ancient";
@JsonIgnore
public static final String MEDIEVAL = "Medieval";
@JsonIgnore
public static final String MODERN = "Modern";
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Wonder.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString()
@JsonTypeName("wonder")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Wonder implements Item {
@JsonIgnore
public static final String ANCIENT = "Ancient";
@JsonIgnore
public static final String MEDIEVAL = "Medieval";
@JsonIgnore
public static final String MODERN = "Modern";
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Village.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("village")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Village implements Item, Tradable, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Village.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("village")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Village implements Item, Tradable, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Tile.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("tile")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Tile implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Tile.java
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("tile")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Tile implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/excel/Key.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
| import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import no.asgari.civilization.server.model.GameType; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.excel;
/**
* To be used in CacheLoader as key
*/
@Data
@NoArgsConstructor
public class Key {
| // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
// Path: src/main/java/no/asgari/civilization/server/excel/Key.java
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import no.asgari.civilization.server.model.GameType;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.excel;
/**
* To be used in CacheLoader as key
*/
@Data
@NoArgsConstructor
public class Key {
| private GameType gameType; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/excel/Key.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
| import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import no.asgari.civilization.server.model.GameType; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.excel;
/**
* To be used in CacheLoader as key
*/
@Data
@NoArgsConstructor
public class Key {
private GameType gameType; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
// Path: src/main/java/no/asgari/civilization/server/excel/Key.java
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import no.asgari.civilization.server.model.GameType;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.excel;
/**
* To be used in CacheLoader as key
*/
@Data
@NoArgsConstructor
public class Key {
private GameType gameType; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/SocialPolicy.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | package no.asgari.civilization.server.model;
@Getter
@Setter
@ToString()
@JsonTypeName("socialpolicy")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class SocialPolicy implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/SocialPolicy.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
package no.asgari.civilization.server.model;
@Getter
@Setter
@ToString()
@JsonTypeName("socialpolicy")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class SocialPolicy implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/PbfDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@Data
@JsonRootName("pbfDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class PbfDTO {
@NotEmpty
private String id;
@NotBlank
private String name; | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
// Path: src/main/java/no/asgari/civilization/server/dto/PbfDTO.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@Data
@JsonRootName("pbfDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class PbfDTO {
@NotEmpty
private String id;
@NotBlank
private String name; | private GameType type; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Civ.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("civ")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
public class Civ implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // id of the player which owns this item | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Civ.java
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("civ")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
public class Civ implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // id of the player which owns this item | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/misc/CivUtil.java | // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Playerhand;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.misc;
public class CivUtil {
public static <T> Stream<T> streamFromIterable(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), false);
}
| // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/main/java/no/asgari/civilization/server/misc/CivUtil.java
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Playerhand;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.misc;
public class CivUtil {
public static <T> Stream<T> streamFromIterable(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), false);
}
| public static boolean shouldSendEmailInGame(Playerhand player) { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/misc/CivUtil.java | // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Playerhand;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.misc;
public class CivUtil {
public static <T> Stream<T> streamFromIterable(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), false);
}
public static boolean shouldSendEmailInGame(Playerhand player) {
//30 min
int min = 60 * 30;
if (shouldSend(player.getIfEmailSent(), min)) {
player.setEmailSent(LocalDateTime.now());
return true;
}
return false;
}
| // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/main/java/no/asgari/civilization/server/misc/CivUtil.java
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.model.Playerhand;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.misc;
public class CivUtil {
public static <T> Stream<T> streamFromIterable(Iterable<T> in) {
return StreamSupport.stream(in.spliterator(), false);
}
public static boolean shouldSendEmailInGame(Playerhand player) {
//30 min
int min = 60 * 30;
if (shouldSend(player.getIfEmailSent(), min)) {
player.setEmailSent(LocalDateTime.now());
return true;
}
return false;
}
| public static boolean shouldSendEmail(Player player) { |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/excel/ItemReaderTest.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Tech.java
// @JsonRootName("tech")
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"name"})
// public class Tech implements Item, Level, Image {
// @JsonIgnore
// public static final int LEVEL_1 = 1;
// @JsonIgnore
// public static final int LEVEL_2 = 2;
// @JsonIgnore
// public static final int LEVEL_3 = 3;
// @JsonIgnore
// public static final int LEVEL_4 = 4;
// @JsonIgnore
// public static final int LEVEL_5 = 5;
//
// @JsonIgnore
// public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
//
// @NotEmpty
// private String name;
// private String type;
// private String description;
// private boolean used;
// private boolean hidden = true;
// private String ownerId;
// private int level;
// private String image;
// private SheetName sheetName;
// private int itemNumber;
//
// public Tech(String name, int level) {
// this.name = name;
// this.level = level;
// hidden = true;
// }
//
// public Tech(String name, int level, int itemNumber) {
// this.name = name;
// this.level = level;
// hidden = true;
// this.itemNumber = itemNumber;
// }
//
// @Override
// public SheetName getSheetName() {
// switch (this.level) {
// case LEVEL_1:
// return sheetName = SheetName.LEVEL_1_TECH;
// case LEVEL_2:
// return sheetName = SheetName.LEVEL_2_TECH;
// case LEVEL_3:
// return sheetName = SheetName.LEVEL_3_TECH;
// case LEVEL_4:
// return sheetName = SheetName.LEVEL_4_TECH;
// case LEVEL_5:
// return sheetName = SheetName.LEVEL_5_TECH;
// }
//
// throw new IllegalArgumentException("Unknown tech level " + level);
// }
//
// @Override
// public String revealPublic() {
// return getSheetName().getName();
// }
//
// @Override
// public String revealAll() {
// return name;
// }
//
// @Override
// public int compareTo(Spreadsheet o) {
// return getSheetName().compareTo(o.getSheetName());
// }
//
// @JsonGetter("image")
// @Override
// public String getImage() {
// image = name + ".png";
// return image.replaceAll(" ", "");
// }
// }
| import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Tech;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull; | package no.asgari.civilization.server.excel;
public class ItemReaderTest {
@Test
public void readItemsFromExcel() throws IOException {
ItemReader itemReader = new ItemReader();
assertNull(itemReader.shuffledCivs);
assertNull(itemReader.shuffledCultureI);
assertNull(itemReader.shuffledCultureII);
assertNull(itemReader.shuffledCultureIII);
assertNull(itemReader.mountedList);
assertNull(itemReader.artilleryList);
assertNull(itemReader.infantryList);
assertNull(itemReader.aircraftList);
| // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Tech.java
// @JsonRootName("tech")
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"name"})
// public class Tech implements Item, Level, Image {
// @JsonIgnore
// public static final int LEVEL_1 = 1;
// @JsonIgnore
// public static final int LEVEL_2 = 2;
// @JsonIgnore
// public static final int LEVEL_3 = 3;
// @JsonIgnore
// public static final int LEVEL_4 = 4;
// @JsonIgnore
// public static final int LEVEL_5 = 5;
//
// @JsonIgnore
// public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
//
// @NotEmpty
// private String name;
// private String type;
// private String description;
// private boolean used;
// private boolean hidden = true;
// private String ownerId;
// private int level;
// private String image;
// private SheetName sheetName;
// private int itemNumber;
//
// public Tech(String name, int level) {
// this.name = name;
// this.level = level;
// hidden = true;
// }
//
// public Tech(String name, int level, int itemNumber) {
// this.name = name;
// this.level = level;
// hidden = true;
// this.itemNumber = itemNumber;
// }
//
// @Override
// public SheetName getSheetName() {
// switch (this.level) {
// case LEVEL_1:
// return sheetName = SheetName.LEVEL_1_TECH;
// case LEVEL_2:
// return sheetName = SheetName.LEVEL_2_TECH;
// case LEVEL_3:
// return sheetName = SheetName.LEVEL_3_TECH;
// case LEVEL_4:
// return sheetName = SheetName.LEVEL_4_TECH;
// case LEVEL_5:
// return sheetName = SheetName.LEVEL_5_TECH;
// }
//
// throw new IllegalArgumentException("Unknown tech level " + level);
// }
//
// @Override
// public String revealPublic() {
// return getSheetName().getName();
// }
//
// @Override
// public String revealAll() {
// return name;
// }
//
// @Override
// public int compareTo(Spreadsheet o) {
// return getSheetName().compareTo(o.getSheetName());
// }
//
// @JsonGetter("image")
// @Override
// public String getImage() {
// image = name + ".png";
// return image.replaceAll(" ", "");
// }
// }
// Path: src/test/java/no/asgari/civilization/server/excel/ItemReaderTest.java
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Tech;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
package no.asgari.civilization.server.excel;
public class ItemReaderTest {
@Test
public void readItemsFromExcel() throws IOException {
ItemReader itemReader = new ItemReader();
assertNull(itemReader.shuffledCivs);
assertNull(itemReader.shuffledCultureI);
assertNull(itemReader.shuffledCultureII);
assertNull(itemReader.shuffledCultureIII);
assertNull(itemReader.mountedList);
assertNull(itemReader.artilleryList);
assertNull(itemReader.infantryList);
assertNull(itemReader.aircraftList);
| itemReader.readItemsFromExcel(GameType.WAW); |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/excel/ItemReaderTest.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Tech.java
// @JsonRootName("tech")
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"name"})
// public class Tech implements Item, Level, Image {
// @JsonIgnore
// public static final int LEVEL_1 = 1;
// @JsonIgnore
// public static final int LEVEL_2 = 2;
// @JsonIgnore
// public static final int LEVEL_3 = 3;
// @JsonIgnore
// public static final int LEVEL_4 = 4;
// @JsonIgnore
// public static final int LEVEL_5 = 5;
//
// @JsonIgnore
// public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
//
// @NotEmpty
// private String name;
// private String type;
// private String description;
// private boolean used;
// private boolean hidden = true;
// private String ownerId;
// private int level;
// private String image;
// private SheetName sheetName;
// private int itemNumber;
//
// public Tech(String name, int level) {
// this.name = name;
// this.level = level;
// hidden = true;
// }
//
// public Tech(String name, int level, int itemNumber) {
// this.name = name;
// this.level = level;
// hidden = true;
// this.itemNumber = itemNumber;
// }
//
// @Override
// public SheetName getSheetName() {
// switch (this.level) {
// case LEVEL_1:
// return sheetName = SheetName.LEVEL_1_TECH;
// case LEVEL_2:
// return sheetName = SheetName.LEVEL_2_TECH;
// case LEVEL_3:
// return sheetName = SheetName.LEVEL_3_TECH;
// case LEVEL_4:
// return sheetName = SheetName.LEVEL_4_TECH;
// case LEVEL_5:
// return sheetName = SheetName.LEVEL_5_TECH;
// }
//
// throw new IllegalArgumentException("Unknown tech level " + level);
// }
//
// @Override
// public String revealPublic() {
// return getSheetName().getName();
// }
//
// @Override
// public String revealAll() {
// return name;
// }
//
// @Override
// public int compareTo(Spreadsheet o) {
// return getSheetName().compareTo(o.getSheetName());
// }
//
// @JsonGetter("image")
// @Override
// public String getImage() {
// image = name + ".png";
// return image.replaceAll(" ", "");
// }
// }
| import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Tech;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull; | package no.asgari.civilization.server.excel;
public class ItemReaderTest {
@Test
public void readItemsFromExcel() throws IOException {
ItemReader itemReader = new ItemReader();
assertNull(itemReader.shuffledCivs);
assertNull(itemReader.shuffledCultureI);
assertNull(itemReader.shuffledCultureII);
assertNull(itemReader.shuffledCultureIII);
assertNull(itemReader.mountedList);
assertNull(itemReader.artilleryList);
assertNull(itemReader.infantryList);
assertNull(itemReader.aircraftList);
itemReader.readItemsFromExcel(GameType.WAW);
assertThat(itemReader.shuffledCivs).isNotEmpty();
assertThat(itemReader.shuffledCultureI).isNotEmpty();
assertThat(itemReader.shuffledCultureII).isNotEmpty();
assertThat(itemReader.shuffledCultureIII).isNotEmpty();
assertThat(itemReader.shuffledGPs).isNotEmpty();
assertThat(itemReader.shuffledHuts).isNotEmpty();
assertThat(itemReader.shuffledVillages).isNotEmpty();
assertThat(itemReader.modernWonders).isNotEmpty();
assertThat(itemReader.medievalWonders).isNotEmpty();
assertThat(itemReader.ancientWonders).isNotEmpty();
assertThat(itemReader.shuffledTiles).isNotEmpty();
assertThat(itemReader.shuffledCityStates).isNotEmpty();
assertThat(itemReader.allTechs).isNotEmpty(); | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Tech.java
// @JsonRootName("tech")
// @JsonIgnoreProperties(ignoreUnknown = true)
// @Data
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"name"})
// public class Tech implements Item, Level, Image {
// @JsonIgnore
// public static final int LEVEL_1 = 1;
// @JsonIgnore
// public static final int LEVEL_2 = 2;
// @JsonIgnore
// public static final int LEVEL_3 = 3;
// @JsonIgnore
// public static final int LEVEL_4 = 4;
// @JsonIgnore
// public static final int LEVEL_5 = 5;
//
// @JsonIgnore
// public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
//
// @NotEmpty
// private String name;
// private String type;
// private String description;
// private boolean used;
// private boolean hidden = true;
// private String ownerId;
// private int level;
// private String image;
// private SheetName sheetName;
// private int itemNumber;
//
// public Tech(String name, int level) {
// this.name = name;
// this.level = level;
// hidden = true;
// }
//
// public Tech(String name, int level, int itemNumber) {
// this.name = name;
// this.level = level;
// hidden = true;
// this.itemNumber = itemNumber;
// }
//
// @Override
// public SheetName getSheetName() {
// switch (this.level) {
// case LEVEL_1:
// return sheetName = SheetName.LEVEL_1_TECH;
// case LEVEL_2:
// return sheetName = SheetName.LEVEL_2_TECH;
// case LEVEL_3:
// return sheetName = SheetName.LEVEL_3_TECH;
// case LEVEL_4:
// return sheetName = SheetName.LEVEL_4_TECH;
// case LEVEL_5:
// return sheetName = SheetName.LEVEL_5_TECH;
// }
//
// throw new IllegalArgumentException("Unknown tech level " + level);
// }
//
// @Override
// public String revealPublic() {
// return getSheetName().getName();
// }
//
// @Override
// public String revealAll() {
// return name;
// }
//
// @Override
// public int compareTo(Spreadsheet o) {
// return getSheetName().compareTo(o.getSheetName());
// }
//
// @JsonGetter("image")
// @Override
// public String getImage() {
// image = name + ".png";
// return image.replaceAll(" ", "");
// }
// }
// Path: src/test/java/no/asgari/civilization/server/excel/ItemReaderTest.java
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Tech;
import org.junit.Test;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNull;
package no.asgari.civilization.server.excel;
public class ItemReaderTest {
@Test
public void readItemsFromExcel() throws IOException {
ItemReader itemReader = new ItemReader();
assertNull(itemReader.shuffledCivs);
assertNull(itemReader.shuffledCultureI);
assertNull(itemReader.shuffledCultureII);
assertNull(itemReader.shuffledCultureIII);
assertNull(itemReader.mountedList);
assertNull(itemReader.artilleryList);
assertNull(itemReader.infantryList);
assertNull(itemReader.aircraftList);
itemReader.readItemsFromExcel(GameType.WAW);
assertThat(itemReader.shuffledCivs).isNotEmpty();
assertThat(itemReader.shuffledCultureI).isNotEmpty();
assertThat(itemReader.shuffledCultureII).isNotEmpty();
assertThat(itemReader.shuffledCultureIII).isNotEmpty();
assertThat(itemReader.shuffledGPs).isNotEmpty();
assertThat(itemReader.shuffledHuts).isNotEmpty();
assertThat(itemReader.shuffledVillages).isNotEmpty();
assertThat(itemReader.modernWonders).isNotEmpty();
assertThat(itemReader.medievalWonders).isNotEmpty();
assertThat(itemReader.ancientWonders).isNotEmpty();
assertThat(itemReader.shuffledTiles).isNotEmpty();
assertThat(itemReader.shuffledCityStates).isNotEmpty();
assertThat(itemReader.allTechs).isNotEmpty(); | assertThat(itemReader.allTechs).contains(Tech.SPACE_FLIGHT); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Tech.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
/**
* All the Level 1, 2, 3, 4 and Space Flight techs
*/
@JsonRootName("tech")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@NoArgsConstructor
@EqualsAndHashCode(of = {"name"})
public class Tech implements Item, Level, Image {
@JsonIgnore
public static final int LEVEL_1 = 1;
@JsonIgnore
public static final int LEVEL_2 = 2;
@JsonIgnore
public static final int LEVEL_3 = 3;
@JsonIgnore
public static final int LEVEL_4 = 4;
@JsonIgnore
public static final int LEVEL_5 = 5;
@JsonIgnore
public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId;
private int level;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Tech.java
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
/**
* All the Level 1, 2, 3, 4 and Space Flight techs
*/
@JsonRootName("tech")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@NoArgsConstructor
@EqualsAndHashCode(of = {"name"})
public class Tech implements Item, Level, Image {
@JsonIgnore
public static final int LEVEL_1 = 1;
@JsonIgnore
public static final int LEVEL_2 = 2;
@JsonIgnore
public static final int LEVEL_3 = 3;
@JsonIgnore
public static final int LEVEL_4 = 4;
@JsonIgnore
public static final int LEVEL_5 = 5;
@JsonIgnore
public static final Tech SPACE_FLIGHT = new Tech("Space Flight", LEVEL_5, 0);
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId;
private int level;
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/GreatPerson.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = {"name", "type"})
@JsonTypeName("greatperson")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class GreatPerson implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/GreatPerson.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = {"name", "type"})
@JsonTypeName("greatperson")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class GreatPerson implements Item, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/tournament/TournamentPlayer.java | // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Player; | package no.asgari.civilization.server.model.tournament;
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class TournamentPlayer {
private String playerId;
private String username;
private boolean paid;
| // Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/tournament/TournamentPlayer.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Player;
package no.asgari.civilization.server.model.tournament;
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class TournamentPlayer {
private String playerId;
private String username;
private boolean paid;
| public TournamentPlayer(Player player) { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/GameDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id; | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/GameDTO.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id; | private GameType type; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/GameDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id;
private GameType type;
private String name;
private long created;
private String whosTurnIsIt; //username of the players turn
private boolean active;
private String mapLink;
private String assetLink;
private List<GameLogDTO> publicLogs;
private List<GameLogDTO> privateLogs; | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/GameDTO.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id;
private GameType type;
private String name;
private long created;
private String whosTurnIsIt; //username of the players turn
private boolean active;
private String mapLink;
private String assetLink;
private List<GameLogDTO> publicLogs;
private List<GameLogDTO> privateLogs; | private Playerhand player; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/GameDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id;
private GameType type;
private String name;
private long created;
private String whosTurnIsIt; //username of the players turn
private boolean active;
private String mapLink;
private String assetLink;
private List<GameLogDTO> publicLogs;
private List<GameLogDTO> privateLogs;
private Playerhand player; | // Path: src/main/java/no/asgari/civilization/server/model/GameType.java
// public enum GameType {
// BASE("Base Game"), FAF("Fame and Fortune"), WAW("Wisdom and Warfare"), DOC("Dawn of Civilization");
//
// private String label;
//
// GameType(String name) {
// this.label = name;
// }
//
// public static Optional<GameType> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<GameType> found = Stream.of(BASE, FAF, WAW, DOC)
// .filter(type -> type.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// @Override
// public String toString() {
// return label;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Item.java
// public interface Item extends Spreadsheet, Type, Comparable<Spreadsheet> {
//
// /**
// * Either the username or pbf name, both of which must be unique *
// */
// public String getName();
//
// public String getOwnerId();
//
// public void setOwnerId(String owner);
//
// public boolean isHidden();
//
// public void setHidden(boolean hidden);
//
// public boolean isUsed();
//
// public String getDescription();
//
// public int getItemNumber();
//
// public void setItemNumber(int itemNumber);
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/GameDTO.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import no.asgari.civilization.server.model.GameType;
import no.asgari.civilization.server.model.Item;
import no.asgari.civilization.server.model.Playerhand;
import java.util.List;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
/**
* DTO for inside a specific game
*/
@Data
@JsonRootName("gameDTO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameDTO {
private String id;
private GameType type;
private String name;
private long created;
private String whosTurnIsIt; //username of the players turn
private boolean active;
private String mapLink;
private String assetLink;
private List<GameLogDTO> publicLogs;
private List<GameLogDTO> privateLogs;
private Playerhand player; | private List<Item> revealedItems; |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/mongodb/MongoDBTest.java | // Path: src/main/java/no/asgari/civilization/server/model/PBF.java
// @Data
// @JsonRootName(value = "pbf")
// @XmlRootElement
// @JsonInclude
// @JsonIgnoreProperties(ignoreUnknown = true)
// //Perhaps use this when the object keep getting changed, otherwise jackson throws exception when it cannot map
// public class PBF {
// @JsonIgnore
// public static final String COL_NAME = "pbf";
// @JsonIgnore
// public static final String NAME = "name";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// private String name;
// private GameType type;
// private String mapLink;
// private String assetLink;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// private int numOfPlayers;
// private boolean active = true;
// private String winner; //username
// private List<Item> items = Lists.newArrayList();
// private List<Playerhand> players = Lists.newArrayList();
// private List<Tech> techs = Lists.newArrayList();
// private List<SocialPolicy> socialPolicies = new ArrayList<>(8);
//
// //@JsonSerialize(keyUsing=TurnKeySerializer.class)
// //@JsonDeserialize(keyUsing = TurnKeyDeserializer.class)
// private Map<String, PlayerTurn> publicTurns = new HashMap<>();
//
// //Will use these to reshuffle items which are discarded and can be drawn again
// private List<Item> discardedItems = new ArrayList<>();
//
// //If a player leaves, his items and stuff will be put here
// private List<Playerhand> withdrawnPlayers = new ArrayList<>();
//
// private boolean tournament = false;
//
// /**
// * Returns the username of the player who is start of turn
// */
// @JsonIgnore
// public String getNameOfUsersTurn() {
// Optional<Playerhand> optional = players.stream()
// .filter(Playerhand::isYourTurn)
// .findFirst();
//
// if (optional.isPresent()) {
// return optional.get().getUsername();
// }
//
// return "";
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.model.Player;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.WriteResult;
import java.io.IOException;
import static org.junit.Assert.assertNotNull; | package no.asgari.civilization.server.mongodb;
public class MongoDBTest extends AbstractCivilizationTest {
private static Player createPlayer(String username, String pbfId) throws JsonProcessingException {
//The Player object should be cached and retrieved from cache
Player player = new Player();
player.setUsername(username);
player.setPassword(DigestUtils.sha1Hex("foo"));
player.getGameIds().add(pbfId);
WriteResult<Player, String> writeResult = getApp().playerCollection.insert(player);
System.out.println("Saved player " + writeResult.toString());
assertNotNull(writeResult.getSavedId());
return player;
}
@Test
public void printAllPBFGames() throws IOException { | // Path: src/main/java/no/asgari/civilization/server/model/PBF.java
// @Data
// @JsonRootName(value = "pbf")
// @XmlRootElement
// @JsonInclude
// @JsonIgnoreProperties(ignoreUnknown = true)
// //Perhaps use this when the object keep getting changed, otherwise jackson throws exception when it cannot map
// public class PBF {
// @JsonIgnore
// public static final String COL_NAME = "pbf";
// @JsonIgnore
// public static final String NAME = "name";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// private String name;
// private GameType type;
// private String mapLink;
// private String assetLink;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// private int numOfPlayers;
// private boolean active = true;
// private String winner; //username
// private List<Item> items = Lists.newArrayList();
// private List<Playerhand> players = Lists.newArrayList();
// private List<Tech> techs = Lists.newArrayList();
// private List<SocialPolicy> socialPolicies = new ArrayList<>(8);
//
// //@JsonSerialize(keyUsing=TurnKeySerializer.class)
// //@JsonDeserialize(keyUsing = TurnKeyDeserializer.class)
// private Map<String, PlayerTurn> publicTurns = new HashMap<>();
//
// //Will use these to reshuffle items which are discarded and can be drawn again
// private List<Item> discardedItems = new ArrayList<>();
//
// //If a player leaves, his items and stuff will be put here
// private List<Playerhand> withdrawnPlayers = new ArrayList<>();
//
// private boolean tournament = false;
//
// /**
// * Returns the username of the player who is start of turn
// */
// @JsonIgnore
// public String getNameOfUsersTurn() {
// Optional<Playerhand> optional = players.stream()
// .filter(Playerhand::isYourTurn)
// .findFirst();
//
// if (optional.isPresent()) {
// return optional.get().getUsername();
// }
//
// return "";
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
// Path: src/test/java/no/asgari/civilization/server/mongodb/MongoDBTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.model.PBF;
import no.asgari.civilization.server.model.Player;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.WriteResult;
import java.io.IOException;
import static org.junit.Assert.assertNotNull;
package no.asgari.civilization.server.mongodb;
public class MongoDBTest extends AbstractCivilizationTest {
private static Player createPlayer(String username, String pbfId) throws JsonProcessingException {
//The Player object should be cached and retrieved from cache
Player player = new Player();
player.setUsername(username);
player.setPassword(DigestUtils.sha1Hex("foo"));
player.getGameIds().add(pbfId);
WriteResult<Player, String> writeResult = getApp().playerCollection.insert(player);
System.out.println("Saved player " + writeResult.toString());
assertNotNull(writeResult.getSavedId());
return player;
}
@Test
public void printAllPBFGames() throws IOException { | @Cleanup DBCursor<PBF> cursor = getApp().pbfCollection.find(); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/DrawDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/Draw.java
// @NoArgsConstructor
// @JsonRootName(value = "draw")
// @Data
// //TODO Draw is not a good name really. Its really more a UndoableItem
// public class Draw<T extends Item> {
// public static final String COL_NAME = "draw";
//
// /**
// * Typically implementation of Unit or Item. Should have #getSheetName() to determine the type
// */
// @NotNull
// private T item;
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created;
// /**
// * The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
// */
// @NotBlank
// private String playerId;
// /**
// * A draw must always belong to a game. The pbf game id
// */
// @NotBlank
// private String pbfId;
// /**
// * If null, then no undo has been performed
// */
// private Undo undo = null;
// private String gameLogId;
//
// public Draw(String pbfId, String playerId) {
// this.pbfId = pbfId;
// this.playerId = playerId;
//
// created = LocalDateTime.now();
// }
//
// /**
// * Returns true if undo has been requested
// */
// @JsonIgnore
// private boolean isUndoInitiated() {
// return undo != null;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Undo.java
// @Data
// @NoArgsConstructor
// @JsonRootName(value = "undo")
// public class Undo {
// /**
// * If undo has been performed *
// */
// private boolean done;
//
// /**
// * Although we can find this number each time, its easier to cache it here *
// */
// private int numberOfVotesRequired;
//
// /**
// * Each player_id gets to vote
// * The value can be true, false or null. Null means not voted yet *
// */
// private Map<String, Boolean> votes = new HashMap<>();
//
// /**
// * Will vote yes for the player since they initiated the request for undo
// *
// * @param numberOfVotesRequired
// * @param playerId
// */
// public Undo(int numberOfVotesRequired, String playerId) {
// this.numberOfVotesRequired = numberOfVotesRequired;
// done = false;
// vote(playerId, Boolean.TRUE);
// }
//
// /**
// * Return the number of votes
// */
// @JsonIgnore
// public int numberOfVotesPerformed() {
// return votes.size();
// }
//
// @JsonIgnore
// public void vote(String playerId, Boolean vote) {
// votes.put(playerId, vote);
// }
//
// /**
// * Get the number of votes remaining
// */
// @JsonIgnore
// public int votesRemaining() {
// return Math.abs(votes.size() - numberOfVotesRequired);
// }
//
// /**
// * All must agree for draw to be performed.
// * If absent/empty, then all players have not voted
// */
// @JsonIgnore
// public Optional<Boolean> getResultOfVotes() {
// if (votesRemaining() != 0) return Optional.empty();
//
// if (getVotes().containsValue(Boolean.FALSE)) return Optional.of(Boolean.FALSE);
//
//
// return Optional.of(Boolean.TRUE);
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.Undo;
import org.hibernate.validator.constraints.NotBlank;
import java.time.LocalDateTime; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName(value = "draw")
@Data
public class DrawDTO {
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;
/**
* The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
*/
@NotBlank
private String playerId;
/**
* A draw must always belong to a game. The pbf game id
*/
@NotBlank
private String pbfId;
/**
* If null, then no undo has been performed
*/ | // Path: src/main/java/no/asgari/civilization/server/model/Draw.java
// @NoArgsConstructor
// @JsonRootName(value = "draw")
// @Data
// //TODO Draw is not a good name really. Its really more a UndoableItem
// public class Draw<T extends Item> {
// public static final String COL_NAME = "draw";
//
// /**
// * Typically implementation of Unit or Item. Should have #getSheetName() to determine the type
// */
// @NotNull
// private T item;
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created;
// /**
// * The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
// */
// @NotBlank
// private String playerId;
// /**
// * A draw must always belong to a game. The pbf game id
// */
// @NotBlank
// private String pbfId;
// /**
// * If null, then no undo has been performed
// */
// private Undo undo = null;
// private String gameLogId;
//
// public Draw(String pbfId, String playerId) {
// this.pbfId = pbfId;
// this.playerId = playerId;
//
// created = LocalDateTime.now();
// }
//
// /**
// * Returns true if undo has been requested
// */
// @JsonIgnore
// private boolean isUndoInitiated() {
// return undo != null;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Undo.java
// @Data
// @NoArgsConstructor
// @JsonRootName(value = "undo")
// public class Undo {
// /**
// * If undo has been performed *
// */
// private boolean done;
//
// /**
// * Although we can find this number each time, its easier to cache it here *
// */
// private int numberOfVotesRequired;
//
// /**
// * Each player_id gets to vote
// * The value can be true, false or null. Null means not voted yet *
// */
// private Map<String, Boolean> votes = new HashMap<>();
//
// /**
// * Will vote yes for the player since they initiated the request for undo
// *
// * @param numberOfVotesRequired
// * @param playerId
// */
// public Undo(int numberOfVotesRequired, String playerId) {
// this.numberOfVotesRequired = numberOfVotesRequired;
// done = false;
// vote(playerId, Boolean.TRUE);
// }
//
// /**
// * Return the number of votes
// */
// @JsonIgnore
// public int numberOfVotesPerformed() {
// return votes.size();
// }
//
// @JsonIgnore
// public void vote(String playerId, Boolean vote) {
// votes.put(playerId, vote);
// }
//
// /**
// * Get the number of votes remaining
// */
// @JsonIgnore
// public int votesRemaining() {
// return Math.abs(votes.size() - numberOfVotesRequired);
// }
//
// /**
// * All must agree for draw to be performed.
// * If absent/empty, then all players have not voted
// */
// @JsonIgnore
// public Optional<Boolean> getResultOfVotes() {
// if (votesRemaining() != 0) return Optional.empty();
//
// if (getVotes().containsValue(Boolean.FALSE)) return Optional.of(Boolean.FALSE);
//
//
// return Optional.of(Boolean.TRUE);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/DrawDTO.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.Undo;
import org.hibernate.validator.constraints.NotBlank;
import java.time.LocalDateTime;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName(value = "draw")
@Data
public class DrawDTO {
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;
/**
* The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
*/
@NotBlank
private String playerId;
/**
* A draw must always belong to a game. The pbf game id
*/
@NotBlank
private String pbfId;
/**
* If null, then no undo has been performed
*/ | private Undo undo = null; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/DrawDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/Draw.java
// @NoArgsConstructor
// @JsonRootName(value = "draw")
// @Data
// //TODO Draw is not a good name really. Its really more a UndoableItem
// public class Draw<T extends Item> {
// public static final String COL_NAME = "draw";
//
// /**
// * Typically implementation of Unit or Item. Should have #getSheetName() to determine the type
// */
// @NotNull
// private T item;
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created;
// /**
// * The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
// */
// @NotBlank
// private String playerId;
// /**
// * A draw must always belong to a game. The pbf game id
// */
// @NotBlank
// private String pbfId;
// /**
// * If null, then no undo has been performed
// */
// private Undo undo = null;
// private String gameLogId;
//
// public Draw(String pbfId, String playerId) {
// this.pbfId = pbfId;
// this.playerId = playerId;
//
// created = LocalDateTime.now();
// }
//
// /**
// * Returns true if undo has been requested
// */
// @JsonIgnore
// private boolean isUndoInitiated() {
// return undo != null;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Undo.java
// @Data
// @NoArgsConstructor
// @JsonRootName(value = "undo")
// public class Undo {
// /**
// * If undo has been performed *
// */
// private boolean done;
//
// /**
// * Although we can find this number each time, its easier to cache it here *
// */
// private int numberOfVotesRequired;
//
// /**
// * Each player_id gets to vote
// * The value can be true, false or null. Null means not voted yet *
// */
// private Map<String, Boolean> votes = new HashMap<>();
//
// /**
// * Will vote yes for the player since they initiated the request for undo
// *
// * @param numberOfVotesRequired
// * @param playerId
// */
// public Undo(int numberOfVotesRequired, String playerId) {
// this.numberOfVotesRequired = numberOfVotesRequired;
// done = false;
// vote(playerId, Boolean.TRUE);
// }
//
// /**
// * Return the number of votes
// */
// @JsonIgnore
// public int numberOfVotesPerformed() {
// return votes.size();
// }
//
// @JsonIgnore
// public void vote(String playerId, Boolean vote) {
// votes.put(playerId, vote);
// }
//
// /**
// * Get the number of votes remaining
// */
// @JsonIgnore
// public int votesRemaining() {
// return Math.abs(votes.size() - numberOfVotesRequired);
// }
//
// /**
// * All must agree for draw to be performed.
// * If absent/empty, then all players have not voted
// */
// @JsonIgnore
// public Optional<Boolean> getResultOfVotes() {
// if (votesRemaining() != 0) return Optional.empty();
//
// if (getVotes().containsValue(Boolean.FALSE)) return Optional.of(Boolean.FALSE);
//
//
// return Optional.of(Boolean.TRUE);
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.Undo;
import org.hibernate.validator.constraints.NotBlank;
import java.time.LocalDateTime; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName(value = "draw")
@Data
public class DrawDTO {
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;
/**
* The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
*/
@NotBlank
private String playerId;
/**
* A draw must always belong to a game. The pbf game id
*/
@NotBlank
private String pbfId;
/**
* If null, then no undo has been performed
*/
private Undo undo = null;
private boolean hidden;
| // Path: src/main/java/no/asgari/civilization/server/model/Draw.java
// @NoArgsConstructor
// @JsonRootName(value = "draw")
// @Data
// //TODO Draw is not a good name really. Its really more a UndoableItem
// public class Draw<T extends Item> {
// public static final String COL_NAME = "draw";
//
// /**
// * Typically implementation of Unit or Item. Should have #getSheetName() to determine the type
// */
// @NotNull
// private T item;
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created;
// /**
// * The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
// */
// @NotBlank
// private String playerId;
// /**
// * A draw must always belong to a game. The pbf game id
// */
// @NotBlank
// private String pbfId;
// /**
// * If null, then no undo has been performed
// */
// private Undo undo = null;
// private String gameLogId;
//
// public Draw(String pbfId, String playerId) {
// this.pbfId = pbfId;
// this.playerId = playerId;
//
// created = LocalDateTime.now();
// }
//
// /**
// * Returns true if undo has been requested
// */
// @JsonIgnore
// private boolean isUndoInitiated() {
// return undo != null;
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Undo.java
// @Data
// @NoArgsConstructor
// @JsonRootName(value = "undo")
// public class Undo {
// /**
// * If undo has been performed *
// */
// private boolean done;
//
// /**
// * Although we can find this number each time, its easier to cache it here *
// */
// private int numberOfVotesRequired;
//
// /**
// * Each player_id gets to vote
// * The value can be true, false or null. Null means not voted yet *
// */
// private Map<String, Boolean> votes = new HashMap<>();
//
// /**
// * Will vote yes for the player since they initiated the request for undo
// *
// * @param numberOfVotesRequired
// * @param playerId
// */
// public Undo(int numberOfVotesRequired, String playerId) {
// this.numberOfVotesRequired = numberOfVotesRequired;
// done = false;
// vote(playerId, Boolean.TRUE);
// }
//
// /**
// * Return the number of votes
// */
// @JsonIgnore
// public int numberOfVotesPerformed() {
// return votes.size();
// }
//
// @JsonIgnore
// public void vote(String playerId, Boolean vote) {
// votes.put(playerId, vote);
// }
//
// /**
// * Get the number of votes remaining
// */
// @JsonIgnore
// public int votesRemaining() {
// return Math.abs(votes.size() - numberOfVotesRequired);
// }
//
// /**
// * All must agree for draw to be performed.
// * If absent/empty, then all players have not voted
// */
// @JsonIgnore
// public Optional<Boolean> getResultOfVotes() {
// if (votesRemaining() != 0) return Optional.empty();
//
// if (getVotes().containsValue(Boolean.FALSE)) return Optional.of(Boolean.FALSE);
//
//
// return Optional.of(Boolean.TRUE);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/DrawDTO.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Draw;
import no.asgari.civilization.server.model.Undo;
import org.hibernate.validator.constraints.NotBlank;
import java.time.LocalDateTime;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName(value = "draw")
@Data
public class DrawDTO {
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime created;
/**
* The user that made the draw. Its always a player that initiates a draw, so this cannot be blank.
*/
@NotBlank
private String playerId;
/**
* A draw must always belong to a game. The pbf game id
*/
@NotBlank
private String pbfId;
/**
* If null, then no undo has been performed
*/
private Undo undo = null;
private boolean hidden;
| public DrawDTO(Draw draw) { |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/CultureII.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("cultureII")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureII implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // player_id
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/CultureII.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("cultureII")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureII implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // player_id
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/application/CivilizationApplication.java | // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
| import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mongodb.*;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.java8.Java8Bundle;
import io.dropwizard.java8.auth.AuthFactory;
import io.dropwizard.java8.auth.CachingAuthenticator;
import io.dropwizard.java8.auth.basic.BasicAuthFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Chat;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.resource.*;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.hk2.utilities.Binder;
import org.mongojack.JacksonDBCollection;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static org.eclipse.jetty.servlets.CrossOriginFilter.*; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.application;
@Log4j
@SuppressWarnings("unchecked")
public class CivilizationApplication extends Application<CivilizationConfiguration> {
public static void main(String[] args) throws Exception {
if (args == null || args.length == 0) {
new CivilizationApplication().run("server", "src/main/resources/config.yml");
} else {
new CivilizationApplication().run(args);
}
}
@Override
public void initialize(Bootstrap<CivilizationConfiguration> bootstrap) {
bootstrap.addBundle(new Java8Bundle());
bootstrap.addBundle(new AssetsBundle());
}
@Override
public void run(CivilizationConfiguration configuration, Environment environment) throws Exception {
DB db;
MongoClient mongo;
if (!Strings.isNullOrEmpty(configuration.mongouri)) {
MongoClientURI clientURI = new MongoClientURI(configuration.mongouri);
mongo = new MongoClient(clientURI);
db = mongo.getDB(Objects.requireNonNull(clientURI.getDatabase()));
} else {
mongo = new MongoClient(configuration.mongohost, configuration.mongoport);
db = mongo.getDB(configuration.mongodb);
}
MongoManaged mongoManaged = new MongoManaged(mongo);
environment.lifecycle().manage(mongoManaged);
| // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/application/CivilizationApplication.java
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mongodb.*;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.java8.Java8Bundle;
import io.dropwizard.java8.auth.AuthFactory;
import io.dropwizard.java8.auth.CachingAuthenticator;
import io.dropwizard.java8.auth.basic.BasicAuthFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Chat;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.resource.*;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.hk2.utilities.Binder;
import org.mongojack.JacksonDBCollection;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static org.eclipse.jetty.servlets.CrossOriginFilter.*;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.application;
@Log4j
@SuppressWarnings("unchecked")
public class CivilizationApplication extends Application<CivilizationConfiguration> {
public static void main(String[] args) throws Exception {
if (args == null || args.length == 0) {
new CivilizationApplication().run("server", "src/main/resources/config.yml");
} else {
new CivilizationApplication().run(args);
}
}
@Override
public void initialize(Bootstrap<CivilizationConfiguration> bootstrap) {
bootstrap.addBundle(new Java8Bundle());
bootstrap.addBundle(new AssetsBundle());
}
@Override
public void run(CivilizationConfiguration configuration, Environment environment) throws Exception {
DB db;
MongoClient mongo;
if (!Strings.isNullOrEmpty(configuration.mongouri)) {
MongoClientURI clientURI = new MongoClientURI(configuration.mongouri);
mongo = new MongoClient(clientURI);
db = mongo.getDB(Objects.requireNonNull(clientURI.getDatabase()));
} else {
mongo = new MongoClient(configuration.mongohost, configuration.mongoport);
db = mongo.getDB(configuration.mongodb);
}
MongoManaged mongoManaged = new MongoManaged(mongo);
environment.lifecycle().manage(mongoManaged);
| JacksonDBCollection<Player, String> playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/application/CivilizationApplication.java | // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
| import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mongodb.*;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.java8.Java8Bundle;
import io.dropwizard.java8.auth.AuthFactory;
import io.dropwizard.java8.auth.CachingAuthenticator;
import io.dropwizard.java8.auth.basic.BasicAuthFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Chat;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.resource.*;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.hk2.utilities.Binder;
import org.mongojack.JacksonDBCollection;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static org.eclipse.jetty.servlets.CrossOriginFilter.*; | } else {
new CivilizationApplication().run(args);
}
}
@Override
public void initialize(Bootstrap<CivilizationConfiguration> bootstrap) {
bootstrap.addBundle(new Java8Bundle());
bootstrap.addBundle(new AssetsBundle());
}
@Override
public void run(CivilizationConfiguration configuration, Environment environment) throws Exception {
DB db;
MongoClient mongo;
if (!Strings.isNullOrEmpty(configuration.mongouri)) {
MongoClientURI clientURI = new MongoClientURI(configuration.mongouri);
mongo = new MongoClient(clientURI);
db = mongo.getDB(Objects.requireNonNull(clientURI.getDatabase()));
} else {
mongo = new MongoClient(configuration.mongohost, configuration.mongoport);
db = mongo.getDB(configuration.mongodb);
}
MongoManaged mongoManaged = new MongoManaged(mongo);
environment.lifecycle().manage(mongoManaged);
JacksonDBCollection<Player, String> playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
//JacksonDBCollection<PBF, String> pbfCollection = JacksonDBCollection.wrap(db.getCollection(PBF.COL_NAME), PBF.class, String.class); | // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
// Path: src/main/java/no/asgari/civilization/server/application/CivilizationApplication.java
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.mongodb.*;
import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.auth.basic.BasicCredentials;
import io.dropwizard.java8.Java8Bundle;
import io.dropwizard.java8.auth.AuthFactory;
import io.dropwizard.java8.auth.CachingAuthenticator;
import io.dropwizard.java8.auth.basic.BasicAuthFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.model.Chat;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.resource.*;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.glassfish.hk2.utilities.Binder;
import org.mongojack.JacksonDBCollection;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static org.eclipse.jetty.servlets.CrossOriginFilter.*;
} else {
new CivilizationApplication().run(args);
}
}
@Override
public void initialize(Bootstrap<CivilizationConfiguration> bootstrap) {
bootstrap.addBundle(new Java8Bundle());
bootstrap.addBundle(new AssetsBundle());
}
@Override
public void run(CivilizationConfiguration configuration, Environment environment) throws Exception {
DB db;
MongoClient mongo;
if (!Strings.isNullOrEmpty(configuration.mongouri)) {
MongoClientURI clientURI = new MongoClientURI(configuration.mongouri);
mongo = new MongoClient(clientURI);
db = mongo.getDB(Objects.requireNonNull(clientURI.getDatabase()));
} else {
mongo = new MongoClient(configuration.mongohost, configuration.mongoport);
db = mongo.getDB(configuration.mongodb);
}
MongoManaged mongoManaged = new MongoManaged(mongo);
environment.lifecycle().manage(mongoManaged);
JacksonDBCollection<Player, String> playerCollection = JacksonDBCollection.wrap(db.getCollection(Player.COL_NAME), Player.class, String.class);
//JacksonDBCollection<PBF, String> pbfCollection = JacksonDBCollection.wrap(db.getCollection(PBF.COL_NAME), PBF.class, String.class); | JacksonDBCollection<Chat, String> chatCollection = JacksonDBCollection.wrap(db.getCollection(Chat.COL_NAME), Chat.class, String.class); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Citystate.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@ToString(of = "name")
@Getter
@Setter
@JsonTypeName("citystate")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "type", "description"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Citystate implements Item, Image {
@JsonProperty
@NotEmpty
private String name;
@JsonProperty
private String type;
@JsonProperty
private String description;
@JsonProperty
private boolean used;
@JsonProperty
private boolean hidden = true;
@JsonProperty
private String ownerId; // (playerId)
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Citystate.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@ToString(of = "name")
@Getter
@Setter
@JsonTypeName("citystate")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "type", "description"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Citystate implements Item, Image {
@JsonProperty
@NotEmpty
private String name;
@JsonProperty
private String type;
@JsonProperty
private String description;
@JsonProperty
private boolean used;
@JsonProperty
private boolean hidden = true;
@JsonProperty
private String ownerId; // (playerId)
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/resource/AuthResourceTest.java | // Path: src/main/java/no/asgari/civilization/server/dto/ForgotpassDTO.java
// @Data
// @JsonRootName(value = "forgotpassDTO")
// public class ForgotpassDTO {
// @NotEmpty
// @Email
// private String email;
//
// @NotNull
// private String newpassword;
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.dto.ForgotpassDTO;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.apache.commons.codec.digest.DigestUtils;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat; | package no.asgari.civilization.server.resource;
public class AuthResourceTest extends AbstractCivilizationTest {
protected static String BASE_URL = String.format("http://localhost:%d/api", RULE.getLocalPort());
@Test
public void shouldGet403WithWrongUsernamePass() {
Form form = new Form("username", "cash1981");
form.param("password", "fifafoo");
Response response = client().target(UriBuilder.fromPath(BASE_URL + "/auth/login").build())
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.FORBIDDEN_403);
}
@Test
public void shouldLoginCorrectly() {
Form form = new Form();
form.param("username", "cash1981").param("password", "foo");
Response response = client().target(BASE_URL + "/auth/login")
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
}
@Test
public void createExistingPlayer() throws JsonProcessingException { | // Path: src/main/java/no/asgari/civilization/server/dto/ForgotpassDTO.java
// @Data
// @JsonRootName(value = "forgotpassDTO")
// public class ForgotpassDTO {
// @NotEmpty
// @Email
// private String email;
//
// @NotNull
// private String newpassword;
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
// Path: src/test/java/no/asgari/civilization/server/resource/AuthResourceTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.dto.ForgotpassDTO;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.apache.commons.codec.digest.DigestUtils;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
package no.asgari.civilization.server.resource;
public class AuthResourceTest extends AbstractCivilizationTest {
protected static String BASE_URL = String.format("http://localhost:%d/api", RULE.getLocalPort());
@Test
public void shouldGet403WithWrongUsernamePass() {
Form form = new Form("username", "cash1981");
form.param("password", "fifafoo");
Response response = client().target(UriBuilder.fromPath(BASE_URL + "/auth/login").build())
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.FORBIDDEN_403);
}
@Test
public void shouldLoginCorrectly() {
Form form = new Form();
form.param("username", "cash1981").param("password", "foo");
Response response = client().target(BASE_URL + "/auth/login")
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK_200);
}
@Test
public void createExistingPlayer() throws JsonProcessingException { | Player one = getApp().playerCollection.findOne(); |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/resource/AuthResourceTest.java | // Path: src/main/java/no/asgari/civilization/server/dto/ForgotpassDTO.java
// @Data
// @JsonRootName(value = "forgotpassDTO")
// public class ForgotpassDTO {
// @NotEmpty
// @Email
// private String email;
//
// @NotNull
// private String newpassword;
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.dto.ForgotpassDTO;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.apache.commons.codec.digest.DigestUtils;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat; | UriBuilder.fromPath(BASE_URL + "/auth/register").build())
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400);
}
@Test
public void createPlayer() throws JsonProcessingException {
@Cleanup DBCursor<Player> foobar = getApp().playerCollection.find(DBQuery.is("username", "foobar"));
if (foobar.hasNext()) {
getApp().playerCollection.removeById(foobar.next().getId());
}
Form form = new Form();
form.param("username", "foobar");
form.param("password", "foobar");
form.param("email", "foobar@mailinator.com");
URI uri = UriBuilder.fromPath(BASE_URL + "/auth/register").build();
Response response = client().target(uri)
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED_201);
assertThat(response.getLocation().getPath()).contains(uri.getPath());
}
@Test
public void verifyPassword() throws Exception { | // Path: src/main/java/no/asgari/civilization/server/dto/ForgotpassDTO.java
// @Data
// @JsonRootName(value = "forgotpassDTO")
// public class ForgotpassDTO {
// @NotEmpty
// @Email
// private String email;
//
// @NotNull
// private String newpassword;
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Player.java
// @Data
// @JsonRootName("player")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Player {
// @JsonIgnore
// public static final String COL_NAME = "player";
// @JsonIgnore
// public static final String USERNAME = "username";
// @JsonIgnore
// public static final String EMAIL = "email";
//
// @ObjectId
// @Id
// private String id;
//
// @NotBlank
// //Unique
// private String username;
//
// @Email
// private String email;
//
// private boolean disableEmail = false;
//
// @NotBlank
// private String password;
//
// private String newPassword;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// /**
// * Set of unique active games This may be reduntant as it can be calculated by looping through all pbfs.players and finding match.
// */
// private Set<String> gameIds = new HashSet<>();
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
// }
//
// Path: src/test/java/no/asgari/civilization/server/mongodb/AbstractCivilizationTest.java
// public abstract class AbstractCivilizationTest {
//
// static {
// LoggingFactory.bootstrap();
// }
//
// @ClassRule
// public static final DropwizardAppRule<CivilizationTestConfiguration> RULE = new DropwizardAppRule<>(CivilizationIntegrationTestApplication.class, "src/main/resources/config-test.yml");
//
// protected static CivilizationIntegrationTestApplication getApp() {
// return RULE.getApplication();
// }
//
// protected static String getUsernameAndPassEncoded() {
// return "Basic " + B64Code.encode("cash1981" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getAdminEncoded() {
// return "Basic " + B64Code.encode("admin" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static String getItchiEncoded() {
// return "Basic " + B64Code.encode("Itchi" + ":" + "foo", StringUtil.__ISO_8859_1);
// }
//
// protected static Client client() {
// Client client = ClientBuilder.newClient();
// client.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
// return client;
// }
//
// }
// Path: src/test/java/no/asgari/civilization/server/resource/AuthResourceTest.java
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Cleanup;
import no.asgari.civilization.server.dto.ForgotpassDTO;
import no.asgari.civilization.server.model.Player;
import no.asgari.civilization.server.mongodb.AbstractCivilizationTest;
import org.apache.commons.codec.digest.DigestUtils;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.Test;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
UriBuilder.fromPath(BASE_URL + "/auth/register").build())
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST_400);
}
@Test
public void createPlayer() throws JsonProcessingException {
@Cleanup DBCursor<Player> foobar = getApp().playerCollection.find(DBQuery.is("username", "foobar"));
if (foobar.hasNext()) {
getApp().playerCollection.removeById(foobar.next().getId());
}
Form form = new Form();
form.param("username", "foobar");
form.param("password", "foobar");
form.param("email", "foobar@mailinator.com");
URI uri = UriBuilder.fromPath(BASE_URL + "/auth/register").build();
Response response = client().target(uri)
.request()
.post(Entity.form(form));
assertThat(response.getStatus()).isEqualTo(HttpStatus.CREATED_201);
assertThat(response.getLocation().getPath()).contains(uri.getPath());
}
@Test
public void verifyPassword() throws Exception { | ForgotpassDTO dto = new ForgotpassDTO(); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Spreadsheet.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import no.asgari.civilization.server.SheetName; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Citystate.class, name = "citystate"),
@JsonSubTypes.Type(value = Civ.class, name = "civ"),
@JsonSubTypes.Type(value = CultureI.class, name = "cultureI"),
@JsonSubTypes.Type(value = CultureII.class, name = "cultureII"),
@JsonSubTypes.Type(value = CultureIII.class, name = "cultureIII"),
@JsonSubTypes.Type(value = GreatPerson.class, name = "greatperson"),
@JsonSubTypes.Type(value = Hut.class, name = "hut"),
@JsonSubTypes.Type(value = Tile.class, name = "tile"),
@JsonSubTypes.Type(value = Village.class, name = "village"),
@JsonSubTypes.Type(value = Wonder.class, name = "wonder"),
@JsonSubTypes.Type(value = Infantry.class, name = "infantry"),
@JsonSubTypes.Type(value = Mounted.class, name = "mounted"),
@JsonSubTypes.Type(value = Artillery.class, name = "artillery"),
@JsonSubTypes.Type(value = Aircraft.class, name = "aircraft"),
@JsonSubTypes.Type(value = Tech.class, name = "tech"),
@JsonSubTypes.Type(value = SocialPolicy.class, name = "socialpolicy")
})
public interface Spreadsheet {
| // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Spreadsheet.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import no.asgari.civilization.server.SheetName;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Citystate.class, name = "citystate"),
@JsonSubTypes.Type(value = Civ.class, name = "civ"),
@JsonSubTypes.Type(value = CultureI.class, name = "cultureI"),
@JsonSubTypes.Type(value = CultureII.class, name = "cultureII"),
@JsonSubTypes.Type(value = CultureIII.class, name = "cultureIII"),
@JsonSubTypes.Type(value = GreatPerson.class, name = "greatperson"),
@JsonSubTypes.Type(value = Hut.class, name = "hut"),
@JsonSubTypes.Type(value = Tile.class, name = "tile"),
@JsonSubTypes.Type(value = Village.class, name = "village"),
@JsonSubTypes.Type(value = Wonder.class, name = "wonder"),
@JsonSubTypes.Type(value = Infantry.class, name = "infantry"),
@JsonSubTypes.Type(value = Mounted.class, name = "mounted"),
@JsonSubTypes.Type(value = Artillery.class, name = "artillery"),
@JsonSubTypes.Type(value = Aircraft.class, name = "aircraft"),
@JsonSubTypes.Type(value = Tech.class, name = "tech"),
@JsonSubTypes.Type(value = SocialPolicy.class, name = "socialpolicy")
})
public interface Spreadsheet {
| public abstract SheetName getSheetName(); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/dto/ChatDTO.java | // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Chat; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName("chat")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class ChatDTO {
private String id;
private String pbfId;
private String username;
private String message;
private String color;
private long created;
public ChatDTO(String id, String pbfId, String username, String message, String color, long createdInMillis) {
this.id = id;
this.pbfId = pbfId;
this.username = username;
this.message = message;
this.created = createdInMillis;
this.color = color;
}
public ChatDTO(String username, String message, long createdInMillis) {
this.username = username;
this.message = message;
this.created = createdInMillis;
}
| // Path: src/main/java/no/asgari/civilization/server/model/Chat.java
// @Data
// @JsonRootName("chat")
// @NoArgsConstructor
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Chat {
// public static final String COL_NAME = "chat";
// public static final String PBFID = "pbfId";
//
// @Id
// @ObjectId
// private String id;
//
// private String pbfId;
//
// @NotNull
// private String username;
//
// @NotEmpty
// private String message;
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime created = LocalDateTime.now();
//
// @JsonIgnore
// public long getCreatedInMillis() {
// return created.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
// }
// }
// Path: src/main/java/no/asgari/civilization/server/dto/ChatDTO.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.asgari.civilization.server.model.Chat;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.dto;
@NoArgsConstructor
@JsonRootName("chat")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class ChatDTO {
private String id;
private String pbfId;
private String username;
private String message;
private String color;
private long created;
public ChatDTO(String id, String pbfId, String username, String message, String color, long createdInMillis) {
this.id = id;
this.pbfId = pbfId;
this.username = username;
this.message = message;
this.created = createdInMillis;
this.color = color;
}
public ChatDTO(String username, String message, long createdInMillis) {
this.username = username;
this.message = message;
this.created = createdInMillis;
}
| public ChatDTO(Chat chat) { |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/misc/MiscTest.java | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import no.asgari.civilization.server.dto.MessageDTO;
import no.asgari.civilization.server.model.Playerhand;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package no.asgari.civilization.server.misc;
public class MiscTest {
@Test
public void checkDecoding() throws Exception {
String encodedText = "http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";
String decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("http://w3schools.com/my test.asp?name=ståle&car=saab");
encodedText = "Lets%20get%20going%20foobars";
decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("Lets get going foobars");
}
@Test
public void createEntityFromString() throws Exception {
Response badReq = Response.status(Response.Status.BAD_REQUEST) | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/test/java/no/asgari/civilization/server/misc/MiscTest.java
import no.asgari.civilization.server.dto.MessageDTO;
import no.asgari.civilization.server.model.Playerhand;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package no.asgari.civilization.server.misc;
public class MiscTest {
@Test
public void checkDecoding() throws Exception {
String encodedText = "http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";
String decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("http://w3schools.com/my test.asp?name=ståle&car=saab");
encodedText = "Lets%20get%20going%20foobars";
decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("Lets get going foobars");
}
@Test
public void createEntityFromString() throws Exception {
Response badReq = Response.status(Response.Status.BAD_REQUEST) | .entity(new MessageDTO("foobar")) |
cash1981/civilization-boardgame-rest | src/test/java/no/asgari/civilization/server/misc/MiscTest.java | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
| import no.asgari.civilization.server.dto.MessageDTO;
import no.asgari.civilization.server.model.Playerhand;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; | package no.asgari.civilization.server.misc;
public class MiscTest {
@Test
public void checkDecoding() throws Exception {
String encodedText = "http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";
String decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("http://w3schools.com/my test.asp?name=ståle&car=saab");
encodedText = "Lets%20get%20going%20foobars";
decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("Lets get going foobars");
}
@Test
public void createEntityFromString() throws Exception {
Response badReq = Response.status(Response.Status.BAD_REQUEST)
.entity(new MessageDTO("foobar"))
.build();
assertThat(((MessageDTO) badReq.getEntity()).getMessage()).isEqualTo("foobar");
}
@Test
public void checkEpochSecondsForMail() throws Exception { | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
//
// Path: src/main/java/no/asgari/civilization/server/model/Playerhand.java
// @Data
// @JsonRootName("players")
// @NoArgsConstructor
// @EqualsAndHashCode(of = {"username", "playerId"})
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Playerhand implements Comparable<Playerhand> {
// @NotBlank
// //Can consider using the playerId instead or removing @NotBlank
// private String username;
//
// @NotBlank
// private String playerId;
//
// private String email;
//
// private String color;
//
// private Civ civilization; //The chosen civilization
//
// /**
// * Save personal gamenotes
// **/
// private String gamenote;
//
// //Only one starting player each turn
// /**
// * Determines whos turn it is each round *
// */
// private boolean yourTurn = false;
// /**
// * Determines player order (ie: Player 2)
// */
// private int playernumber;
// private boolean gameCreator = false;
//
// private List<Item> items = new ArrayList<>();
// private Set<Tech> techsChosen = new TreeSet<>();
// private List<Unit> barbarians = new ArrayList<>(3);
// private List<Unit> battlehand = new ArrayList<>();
// private List<SocialPolicy> socialPolicies = new ArrayList<>();
// /**
// * Private turns, only made public when they are locked
// */
// private Set<PlayerTurn> playerTurns = new TreeSet<>();
//
// @JsonSerialize(using = LocalDateTimeSerializer.class)
// @JsonDeserialize(using = LocalDateTimeDeserializer.class)
// private LocalDateTime emailSent;
//
// @JsonIgnore
// public static String green() {
// return "Green";
// }
//
// @JsonIgnore
// public static String yellow() {
// return "Yellow";
// }
//
// @JsonIgnore
// public static String purple() {
// return "Purple";
// }
//
// @JsonIgnore
// public static String red() {
// return "Red";
// }
//
// @JsonIgnore
// public static String blue() {
// return "Blue";
// }
//
// @JsonIgnore
// public Optional<LocalDateTime> getIfEmailSent() {
// return Optional.ofNullable(emailSent);
// }
//
// @Override
// public int compareTo(Playerhand o) {
// return o.getUsername().compareTo(o.getUsername());
// }
// }
// Path: src/test/java/no/asgari/civilization/server/misc/MiscTest.java
import no.asgari.civilization.server.dto.MessageDTO;
import no.asgari.civilization.server.model.Playerhand;
import org.junit.Test;
import javax.ws.rs.core.Response;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
package no.asgari.civilization.server.misc;
public class MiscTest {
@Test
public void checkDecoding() throws Exception {
String encodedText = "http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab";
String decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("http://w3schools.com/my test.asp?name=ståle&car=saab");
encodedText = "Lets%20get%20going%20foobars";
decodedText = URLDecoder.decode(encodedText, "UTF-8");
assertThat(decodedText).isEqualTo("Lets get going foobars");
}
@Test
public void createEntityFromString() throws Exception {
Response badReq = Response.status(Response.Status.BAD_REQUEST)
.entity(new MessageDTO("foobar"))
.build();
assertThat(((MessageDTO) badReq.getEntity()).getMessage()).isEqualTo("foobar");
}
@Test
public void checkEpochSecondsForMail() throws Exception { | Playerhand playerhand = new Playerhand(); |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/exception/NoMoreItemsException.java | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
| import no.asgari.civilization.server.dto.MessageDTO;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.exception;
public class NoMoreItemsException extends WebApplicationException {
public NoMoreItemsException(String name) {
super(Response.status(Response.Status.GONE) | // Path: src/main/java/no/asgari/civilization/server/dto/MessageDTO.java
// public class MessageDTO {
//
// private final String message;
//
// @JsonCreator
// public MessageDTO(@JsonProperty("msg") String message) {
// this.message = message;
// }
//
// @JsonProperty("msg")
// public String getMessage() {
// return message;
// }
//
// }
// Path: src/main/java/no/asgari/civilization/server/exception/NoMoreItemsException.java
import no.asgari.civilization.server.dto.MessageDTO;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.exception;
public class NoMoreItemsException extends WebApplicationException {
public NoMoreItemsException(String name) {
super(Response.status(Response.Status.GONE) | .entity(Entity.json(new MessageDTO("No more " + name + " to draw!"))) |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/CultureIII.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("cultureIII")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureIII implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/CultureIII.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("cultureIII")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureIII implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // game_id or player_id (username)
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/CultureI.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("cultureI")
@ToString(of = "name")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureI implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // player_id
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/CultureI.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("cultureI")
@ToString(of = "name")
@NoArgsConstructor
@EqualsAndHashCode(of = {"name", "description", "type"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class CultureI implements Item, Tradable, Image {
@NotEmpty
private String name;
private String description;
private String type;
private boolean used;
private boolean hidden = true;
private String ownerId; // player_id
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Infantry.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("infantry")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Infantry extends Unit implements Image {
private int level = 0;
private int attack;
private int health;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private boolean isInBattle;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Infantry.java
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("infantry")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Infantry extends Unit implements Image {
private int level = 0;
private int attack;
private int health;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private boolean isInBattle;
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Hut.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("hut")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Hut implements Item, Tradable, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Hut.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import no.asgari.civilization.server.SheetName;
import org.hibernate.validator.constraints.NotEmpty;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@ToString(of = "name")
@JsonTypeName("hut")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used"})
@JsonIgnoreProperties(ignoreUnknown = true)
public class Hut implements Item, Tradable, Image {
@NotEmpty
private String name;
private String type;
private String description;
private boolean used;
private boolean hidden = true;
private String ownerId;
private String image; | private SheetName sheetName; |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/model/Mounted.java | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
| import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName; | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("mounted")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Mounted extends Unit implements Image {
private int level = 0;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | // Path: src/main/java/no/asgari/civilization/server/SheetName.java
// public enum SheetName {
// CIV("Civ"), CULTURE_1("Culture I"), CULTURE_2("Culture II"),
// CULTURE_3("Culture III"), GREAT_PERSON("Great Person"), INFANTRY("Infantry"), ARTILLERY("Artillery"), MOUNTED("Mounted"),
// AIRCRAFT("Aircraft"), VILLAGES("Villages"), HUTS("Huts"), WONDERS("Wonders"), ANCIENT_WONDERS("Ancient Wonders"), MEDIEVAL_WONDERS("Medieval Wonders"),
// MODERN_WONDERS("Modern Wonders"), TILES("Tiles"), CITY_STATES("City-states"), LEVEL_1_TECH("Level 1 Tech"), LEVEL_2_TECH("Level 2 Tech"),
// LEVEL_3_TECH("Level 3 Tech"), LEVEL_4_TECH("Level 4 Tech"), LEVEL_5_TECH("Level 5 Tech"), SOCIAL_POLICY("Social Policy");
//
// public static final EnumSet<SheetName> SHEETS =
// EnumSet.of(CIV, CULTURE_1, CULTURE_2, CULTURE_3,
// GREAT_PERSON, INFANTRY, ARTILLERY, MOUNTED, AIRCRAFT,
// VILLAGES, HUTS, WONDERS, ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS, TILES, CITY_STATES,
// LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH, SOCIAL_POLICY);
// public static final EnumSet<SheetName> TECHS = EnumSet.of(LEVEL_1_TECH, LEVEL_2_TECH, LEVEL_3_TECH, LEVEL_4_TECH, LEVEL_5_TECH);
// public static final EnumSet<SheetName> UNITS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED);
// public static final EnumSet<SheetName> CULTURE_CARD = EnumSet.of(CULTURE_1, CULTURE_2, CULTURE_3);
// public static final EnumSet<SheetName> ALL_WONDERS = EnumSet.of(ANCIENT_WONDERS, MEDIEVAL_WONDERS, MODERN_WONDERS);
// public static final EnumSet<SheetName> SHUFFLABLE_ITEMS = EnumSet.of(AIRCRAFT, ARTILLERY, INFANTRY, MOUNTED,
// GREAT_PERSON, CULTURE_1, CULTURE_2, CULTURE_3, CIV);
// private String label;
//
// SheetName(String name) {
// this.label = name;
// }
//
// public static Optional<SheetName> find(String name) {
// String spacesRemovedName = name.replaceAll("\\s", "");
// Optional<SheetName> found = SHEETS.stream()
// .filter(sheet -> sheet.label.replaceAll("\\s", "").equalsIgnoreCase(spacesRemovedName))
// .findFirst();
// if (!found.isPresent()) {
// try {
// return Optional.of(valueOf(name.toUpperCase()));
// } catch (Exception ex) {
// return Optional.empty();
// }
// }
// return found;
// }
//
// public String getName() {
// return label;
// }
// }
// Path: src/main/java/no/asgari/civilization/server/model/Mounted.java
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.asgari.civilization.server.SheetName;
/*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.model;
@Getter
@Setter
@JsonTypeName("mounted")
@NoArgsConstructor
@EqualsAndHashCode(exclude = {"ownerId", "hidden", "used", "itemNumber"}, callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Mounted extends Unit implements Image {
private int level = 0;
private String ownerId;
private boolean hidden = true;
private boolean used;
private boolean killed;
private int attack;
private int health;
private boolean isInBattle;
private String image; | private SheetName sheetName; |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.sql.Connection;
import java.util.List;
import java.util.UUID;
import com.stacksync.commons.models.CommitInfo;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.Item;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.ShareProposalNotCreatedException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.commons.notifications.CommitNotification;
import com.stacksync.syncservice.exceptions.dao.DAOException; | package com.stacksync.syncservice.handler;
public interface SyncHandler {
public CommitNotification doCommit(User user, Workspace workspace, Device device, List<ItemMetadata> items) | // Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SyncHandler.java
import java.sql.Connection;
import java.util.List;
import java.util.UUID;
import com.stacksync.commons.models.CommitInfo;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.Item;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.ShareProposalNotCreatedException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.commons.notifications.CommitNotification;
import com.stacksync.syncservice.exceptions.dao.DAOException;
package com.stacksync.syncservice.handler;
public interface SyncHandler {
public CommitNotification doCommit(User user, Workspace workspace, Device device, List<ItemMetadata> items) | throws DAOException; |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/exceptions/dao/NoGeneratedKeysDAOException.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
| import com.stacksync.syncservice.db.DAOError; | package com.stacksync.syncservice.exceptions.dao;
public class NoGeneratedKeysDAOException extends DAOException {
private static final long serialVersionUID = -2938093497450050090L;
| // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoGeneratedKeysDAOException.java
import com.stacksync.syncservice.db.DAOError;
package com.stacksync.syncservice.exceptions.dao;
public class NoGeneratedKeysDAOException extends DAOException {
private static final long serialVersionUID = -2938093497450050090L;
| public NoGeneratedKeysDAOException(DAOError error) { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
| import com.stacksync.syncservice.db.DAOError; | package com.stacksync.syncservice.exceptions.dao;
public class NoRowsAffectedDAOException extends DAOException {
private static final long serialVersionUID = 356684827372558709L;
| // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
import com.stacksync.syncservice.db.DAOError;
package com.stacksync.syncservice.exceptions.dao;
public class NoRowsAffectedDAOException extends DAOException {
private static final long serialVersionUID = 356684827372558709L;
| public NoRowsAffectedDAOException(DAOError error) { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; | package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
| // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable;
package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
| public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; | package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
| // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable;
package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
| public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; | package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable {
super(pool);
}
@Override
public List<ItemMetadata> doGetChanges(User user, Workspace workspace) {
List<ItemMetadata> responseObjects = new ArrayList<ItemMetadata>();
try {
responseObjects = itemDao.getItemsByWorkspaceId(workspace.getId()); | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable;
package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable {
super(pool);
}
@Override
public List<ItemMetadata> doGetChanges(User user, Workspace workspace) {
List<ItemMetadata> responseObjects = new ArrayList<ItemMetadata>();
try {
responseObjects = itemDao.getItemsByWorkspaceId(workspace.getId()); | } catch (DAOException e) { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; | package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable {
super(pool);
}
@Override
public List<ItemMetadata> doGetChanges(User user, Workspace workspace) {
List<ItemMetadata> responseObjects = new ArrayList<ItemMetadata>();
try {
responseObjects = itemDao.getItemsByWorkspaceId(workspace.getId());
} catch (DAOException e) {
logger.error(e.toString(), e);
}
return responseObjects;
}
@Override
public List<Workspace> doGetWorkspaces(User user) throws NoWorkspacesFoundException {
List<Workspace> workspaces = new ArrayList<Workspace>();
try {
workspaces = workspaceDAO.getByUserId(user.getId());
| // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable;
package com.stacksync.syncservice.handler;
public class SQLSyncHandler extends Handler implements SyncHandler {
private static final Logger logger = Logger.getLogger(SQLSyncHandler.class.getName());
public SQLSyncHandler(ConnectionPool pool) throws SQLException, NoStorageManagerAvailable {
super(pool);
}
@Override
public List<ItemMetadata> doGetChanges(User user, Workspace workspace) {
List<ItemMetadata> responseObjects = new ArrayList<ItemMetadata>();
try {
responseObjects = itemDao.getItemsByWorkspaceId(workspace.getId());
} catch (DAOException e) {
logger.error(e.toString(), e);
}
return responseObjects;
}
@Override
public List<Workspace> doGetWorkspaces(User user) throws NoWorkspacesFoundException {
List<Workspace> workspaces = new ArrayList<Workspace>();
try {
workspaces = workspaceDAO.getByUserId(user.getId());
| } catch (NoResultReturnedDAOException e) { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable; | } catch (DAOException e) {
logger.error(e);
throw new NoWorkspacesFoundException(e);
}
return workspaces;
}
@Override
public UUID doUpdateDevice(Device device) throws UserNotFoundException, DeviceNotValidException,
DeviceNotUpdatedException {
try {
User dbUser = userDao.findById(device.getUser().getId());
device.setUser(dbUser);
} catch (NoResultReturnedDAOException e) {
logger.warn(e);
throw new UserNotFoundException(e);
} catch (DAOException e) {
logger.error(e);
throw new DeviceNotUpdatedException(e);
}
try {
if (device.getId() == null) {
deviceDao.add(device);
} else {
deviceDao.update(device);
} | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/storage/NoStorageManagerAvailable.java
// public class NoStorageManagerAvailable extends Exception {
//
// private static final long serialVersionUID = -2162586363263343293L;
//
// public NoStorageManagerAvailable(String message) {
// super(message);
// }
// }
// Path: src/main/java/com/stacksync/syncservice/handler/SQLSyncHandler.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.ItemMetadata;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.commons.exceptions.DeviceNotUpdatedException;
import com.stacksync.commons.exceptions.DeviceNotValidException;
import com.stacksync.commons.exceptions.NoWorkspacesFoundException;
import com.stacksync.commons.exceptions.UserNotFoundException;
import com.stacksync.commons.exceptions.WorkspaceNotUpdatedException;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
import com.stacksync.syncservice.exceptions.storage.NoStorageManagerAvailable;
} catch (DAOException e) {
logger.error(e);
throw new NoWorkspacesFoundException(e);
}
return workspaces;
}
@Override
public UUID doUpdateDevice(Device device) throws UserNotFoundException, DeviceNotValidException,
DeviceNotUpdatedException {
try {
User dbUser = userDao.findById(device.getUser().getId());
device.setUser(dbUser);
} catch (NoResultReturnedDAOException e) {
logger.warn(e);
throw new UserNotFoundException(e);
} catch (DAOException e) {
logger.error(e);
throw new DeviceNotUpdatedException(e);
}
try {
if (device.getId() == null) {
deviceDao.add(device);
} else {
deviceDao.update(device);
} | } catch (NoRowsAffectedDAOException e) { |
stacksync/sync-service | src/test/java/com/stacksync/syncservice/test/main/ServerTest.java | // Path: src/main/java/com/stacksync/syncservice/SyncServiceDaemon.java
// public class SyncServiceDaemon implements Daemon {
//
// private static final Logger logger = Logger
// .getLogger(SyncServiceDaemon.class.getName());
// private static ConnectionPool pool = null;
// private static XmlRpcSyncServer xmlRpcServer = null;
// private static Broker broker = null;
// private static SyncServiceImp syncService = null;
//
// @Override
// public void init(DaemonContext dc) throws DaemonInitException, Exception {
//
// logger.info(String.format("Initializing StackSync Server v%s...",
// SyncServiceDaemon.getVersion()));
//
// logger.info(String.format("Java VM: %s", System.getProperty("java.vm.name")));
// logger.info(String.format("Java VM version: %s", System.getProperty("java.vm.version")));
// logger.info(String.format("Java Home: %s", System.getProperty("java.home")));
// logger.info(String.format("Java version: %s", System.getProperty("java.version")));
//
// try {
// String[] argv = dc.getArguments();
//
// if (argv.length == 0) {
// logger.error("No config file passed to StackSync Server.");
// System.exit(1);
// }
//
// String configPath = argv[0];
//
// File file = new File(configPath);
// if (!file.exists()) {
// logger.error("'" + configPath + "' file not found");
// System.exit(2);
// }
//
// Config.loadProperties(configPath);
//
// } catch (IOException e) {
// logger.error("Could not load properties file.", e);
// System.exit(7);
// }
//
// try {
//
// String datasource = Config.getDatasource();
// pool = ConnectionPoolFactory.getConnectionPool(datasource);
//
// // it will try to connect to the DB, throws exception if not
// // possible.
// Connection conn = pool.getConnection();
// conn.close();
//
// logger.info("Connection to database succeded");
// } catch (DAOConfigurationException e) {
// logger.error("Connection to database failed.", e);
// System.exit(3);
// } catch (SQLException e) {
// logger.error("Connection to database failed.", e);
// System.exit(4);
// }
//
// logger.info("Connecting to OpenStack Swift...");
//
// try {
// StorageType type;
// if (Config.getSwiftKeystoneProtocol().equals("http")) {
// type = StorageType.SWIFT;
// } else {
// type = StorageType.SWIFT_SSL;
// }
// StorageManager storageManager = StorageFactory.getStorageManager(type);
// storageManager.login();
// logger.info("Connected to OpenStack Swift successfully");
// } catch (Exception e) {
// logger.fatal("Could not connect to Swift.", e);
// System.exit(7);
// }
//
//
// logger.info("Initializing the messaging middleware...");
// try {
// broker = new Broker(Config.getProperties());
// syncService = new SyncServiceImp(broker, pool);
// logger.info("Messaging middleware initialization succeeded");
// } catch (Exception e) {
// logger.error("Could not initialize ObjectMQ.", e);
// System.exit(5);
// }
// }
//
// @Override
// public void start() throws Exception {
//
// try {
// broker.bind(ISyncService.class.getSimpleName(), syncService);
// logger.info("StackSync Server is ready and waiting for messages...");
// } catch (Exception e) {
// logger.fatal("Could not bind queue.", e);
// System.exit(5);
// }
//
// logger.info("Initializing XML RPC...");
// try {
// launchXmlRpc();
// logger.info("XML RPC initialization succeded");
// } catch (Exception e) {
// logger.fatal("Could not initialize XMLRPC.", e);
// System.exit(6);
// }
// }
//
// @Override
// public void stop() throws Exception {
// try {
// broker.stopBroker();
// } catch (Exception e) {
// logger.fatal("Error stoping StackSync Server.", e);
// throw e;
// }
// }
//
// @Override
// public void destroy() {
// broker = null;
// }
//
// private static void launchXmlRpc() throws Exception {
// xmlRpcServer = new XmlRpcSyncServer(Constants.XMLRPC_PORT);
// xmlRpcServer.addHandler("XmlRpcSyncHandler", new XmlRpcSyncHandler(
// broker, pool));
// xmlRpcServer.serve_forever();
// }
//
// private static String getVersion() {
// String path = "/version.properties";
// InputStream stream = Config.class.getResourceAsStream(path);
// if (stream == null) {
// return "UNKNOWN";
// }
// Properties props = new Properties();
// try {
// props.load(stream);
// stream.close();
// return (String) props.get("version");
// } catch (IOException e) {
// return "UNKNOWN";
// }
// }
// }
| import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonController;
import com.stacksync.syncservice.SyncServiceDaemon; | package com.stacksync.syncservice.test.main;
public class ServerTest {
public static void main(String[] args) throws Exception {
| // Path: src/main/java/com/stacksync/syncservice/SyncServiceDaemon.java
// public class SyncServiceDaemon implements Daemon {
//
// private static final Logger logger = Logger
// .getLogger(SyncServiceDaemon.class.getName());
// private static ConnectionPool pool = null;
// private static XmlRpcSyncServer xmlRpcServer = null;
// private static Broker broker = null;
// private static SyncServiceImp syncService = null;
//
// @Override
// public void init(DaemonContext dc) throws DaemonInitException, Exception {
//
// logger.info(String.format("Initializing StackSync Server v%s...",
// SyncServiceDaemon.getVersion()));
//
// logger.info(String.format("Java VM: %s", System.getProperty("java.vm.name")));
// logger.info(String.format("Java VM version: %s", System.getProperty("java.vm.version")));
// logger.info(String.format("Java Home: %s", System.getProperty("java.home")));
// logger.info(String.format("Java version: %s", System.getProperty("java.version")));
//
// try {
// String[] argv = dc.getArguments();
//
// if (argv.length == 0) {
// logger.error("No config file passed to StackSync Server.");
// System.exit(1);
// }
//
// String configPath = argv[0];
//
// File file = new File(configPath);
// if (!file.exists()) {
// logger.error("'" + configPath + "' file not found");
// System.exit(2);
// }
//
// Config.loadProperties(configPath);
//
// } catch (IOException e) {
// logger.error("Could not load properties file.", e);
// System.exit(7);
// }
//
// try {
//
// String datasource = Config.getDatasource();
// pool = ConnectionPoolFactory.getConnectionPool(datasource);
//
// // it will try to connect to the DB, throws exception if not
// // possible.
// Connection conn = pool.getConnection();
// conn.close();
//
// logger.info("Connection to database succeded");
// } catch (DAOConfigurationException e) {
// logger.error("Connection to database failed.", e);
// System.exit(3);
// } catch (SQLException e) {
// logger.error("Connection to database failed.", e);
// System.exit(4);
// }
//
// logger.info("Connecting to OpenStack Swift...");
//
// try {
// StorageType type;
// if (Config.getSwiftKeystoneProtocol().equals("http")) {
// type = StorageType.SWIFT;
// } else {
// type = StorageType.SWIFT_SSL;
// }
// StorageManager storageManager = StorageFactory.getStorageManager(type);
// storageManager.login();
// logger.info("Connected to OpenStack Swift successfully");
// } catch (Exception e) {
// logger.fatal("Could not connect to Swift.", e);
// System.exit(7);
// }
//
//
// logger.info("Initializing the messaging middleware...");
// try {
// broker = new Broker(Config.getProperties());
// syncService = new SyncServiceImp(broker, pool);
// logger.info("Messaging middleware initialization succeeded");
// } catch (Exception e) {
// logger.error("Could not initialize ObjectMQ.", e);
// System.exit(5);
// }
// }
//
// @Override
// public void start() throws Exception {
//
// try {
// broker.bind(ISyncService.class.getSimpleName(), syncService);
// logger.info("StackSync Server is ready and waiting for messages...");
// } catch (Exception e) {
// logger.fatal("Could not bind queue.", e);
// System.exit(5);
// }
//
// logger.info("Initializing XML RPC...");
// try {
// launchXmlRpc();
// logger.info("XML RPC initialization succeded");
// } catch (Exception e) {
// logger.fatal("Could not initialize XMLRPC.", e);
// System.exit(6);
// }
// }
//
// @Override
// public void stop() throws Exception {
// try {
// broker.stopBroker();
// } catch (Exception e) {
// logger.fatal("Error stoping StackSync Server.", e);
// throw e;
// }
// }
//
// @Override
// public void destroy() {
// broker = null;
// }
//
// private static void launchXmlRpc() throws Exception {
// xmlRpcServer = new XmlRpcSyncServer(Constants.XMLRPC_PORT);
// xmlRpcServer.addHandler("XmlRpcSyncHandler", new XmlRpcSyncHandler(
// broker, pool));
// xmlRpcServer.serve_forever();
// }
//
// private static String getVersion() {
// String path = "/version.properties";
// InputStream stream = Config.class.getResourceAsStream(path);
// if (stream == null) {
// return "UNKNOWN";
// }
// Properties props = new Properties();
// try {
// props.load(stream);
// stream.close();
// return (String) props.get("version");
// } catch (IOException e) {
// return "UNKNOWN";
// }
// }
// }
// Path: src/test/java/com/stacksync/syncservice/test/main/ServerTest.java
import org.apache.commons.daemon.DaemonContext;
import org.apache.commons.daemon.DaemonController;
import com.stacksync.syncservice.SyncServiceDaemon;
package com.stacksync.syncservice.test.main;
public class ServerTest {
public static void main(String[] args) throws Exception {
| SyncServiceDaemon daemon = new SyncServiceDaemon(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.