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 |
|---|---|---|---|---|---|---|
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/activities/BaseActivity.java | // Path: app/src/main/java/be/artoria/belfortapp/app/PrefUtils.java
// public class PrefUtils {
// public static final String TAG = "Belfort";
// public static final String DATASET_URL = "https://raw.githubusercontent.com/oSoc14/ArtoriaData/master/poi.json";
//
// private static final String ARG_USER_KEY = "be.artoria.belfort";
// private static final String ARG_DOWNLOAD = "be.artoria.belfort.downloadtimes";
// private static final String ARG_FIRS_TTIME = "be.artoria.belfort.firstTime";
// private static final String ARG_ROUTE = "be.artoria.belfort.route";
// private static final String ARG_LANG = "be.artoria.belfort.lang";
// private static final String ARG_FIRS_PANORAMA_TIME = "be.artoria.belfort.panorama_firstTime";
//
// private static Context CONTEXT;
//
// public static Context getContext()
// {
// return CONTEXT;
// }
//
// public static void initialize(Application application)
// {
// CONTEXT = application;
// }
//
// public static void saveTimeStampDownloads()
// {
// getPrefs()
// .edit()
// .putLong(ARG_DOWNLOAD, System.currentTimeMillis())
// .apply();
// }
//
// public static boolean isFirstTime() {
// return getPrefs().getBoolean(ARG_FIRS_TTIME, true);
// }
//
// public static void setNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_TTIME, false)
// .apply();
// }
//
// public static long getTimeStampDownloads()
// {
// return getPrefs().getLong(ARG_DOWNLOAD, 0);
// }
//
// public static void removeAll()
// {
// getPrefs().edit().clear().apply();
// }
//
// // get preferences
// @SuppressWarnings("NewApi")
// private static SharedPreferences getPrefs()
// {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_MULTI_PROCESS);
// } else {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_PRIVATE);
// }
// }
//
// public static DataManager.Language getLanguage() {
// final Locale locale = getContext().getResources().getConfiguration().locale;
// final String lang = locale.getLanguage();
// if("en".equals(lang)){ return DataManager.Language.ENGLISH;}
// if("fr".equals(lang)){ return DataManager.Language.FRENCH;}
// /* default choice is dutch */
// return DataManager.Language.DUTCH;
// }
//
// public static void saveLanguage(DataManager.Language lang){
// String lng = "nl";//default dutch
// if(lang == DataManager.Language.ENGLISH){lng="en";}
// if(lang == DataManager.Language.FRENCH){lng ="fr";}
// getPrefs().edit().putString(ARG_LANG,lng).apply();
// }
//
// public static void loadLanguage(Context context){
// final String lang = getPrefs().getString(ARG_LANG,"nl");/*Default dutch*/
// final Locale locale = new Locale(lang);
// LanguageChoiceActivity.setLang(locale,context);
// }
//
// public static List<POI> getSavedRoute(){
// final String poiIds = getPrefs().getString(ARG_ROUTE,"");
// final List<POI> toReturn = new ArrayList<POI>();
// if(!poiIds.equals("")){
// final String[] splitted = poiIds.split(",");
// for(String s: splitted){
// try {
// final int id = Integer.parseInt(s);
// final POI toAdd = DataManager.getPOIbyID(id);
// toReturn.add(toAdd);
// }catch(Exception ex){
// //can't parse string to int ....
// }
// }
// }
// return toReturn;
// }
//
// public static void saveRoute(List<POI> route){
// final StringBuilder sb = new StringBuilder();
// for(POI poi : route){
// sb.append(poi.id);
// sb.append(",");
// }
// if(sb.length() > 0) {
// sb.delete(sb.length() - 1, sb.length());
// }
// getPrefs().edit().putString(ARG_ROUTE,sb.toString()).apply();
// }
//
// public static void setPanoramaNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_PANORAMA_TIME, false)
// .apply();
// }
// public static boolean isFirstPanoramaTime() {
// return getPrefs().getBoolean(ARG_FIRS_PANORAMA_TIME, true);
// }
//
// }
| import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.ViewGroup;
import android.view.Window;
import be.artoria.belfortapp.R;
import be.artoria.belfortapp.app.PrefUtils; | package be.artoria.belfortapp.activities;
public class BaseActivity extends ActionBarActivity {
protected static Typeface athelas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar ab = getActionBar();
if(ab != null ) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color2)));
} | // Path: app/src/main/java/be/artoria/belfortapp/app/PrefUtils.java
// public class PrefUtils {
// public static final String TAG = "Belfort";
// public static final String DATASET_URL = "https://raw.githubusercontent.com/oSoc14/ArtoriaData/master/poi.json";
//
// private static final String ARG_USER_KEY = "be.artoria.belfort";
// private static final String ARG_DOWNLOAD = "be.artoria.belfort.downloadtimes";
// private static final String ARG_FIRS_TTIME = "be.artoria.belfort.firstTime";
// private static final String ARG_ROUTE = "be.artoria.belfort.route";
// private static final String ARG_LANG = "be.artoria.belfort.lang";
// private static final String ARG_FIRS_PANORAMA_TIME = "be.artoria.belfort.panorama_firstTime";
//
// private static Context CONTEXT;
//
// public static Context getContext()
// {
// return CONTEXT;
// }
//
// public static void initialize(Application application)
// {
// CONTEXT = application;
// }
//
// public static void saveTimeStampDownloads()
// {
// getPrefs()
// .edit()
// .putLong(ARG_DOWNLOAD, System.currentTimeMillis())
// .apply();
// }
//
// public static boolean isFirstTime() {
// return getPrefs().getBoolean(ARG_FIRS_TTIME, true);
// }
//
// public static void setNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_TTIME, false)
// .apply();
// }
//
// public static long getTimeStampDownloads()
// {
// return getPrefs().getLong(ARG_DOWNLOAD, 0);
// }
//
// public static void removeAll()
// {
// getPrefs().edit().clear().apply();
// }
//
// // get preferences
// @SuppressWarnings("NewApi")
// private static SharedPreferences getPrefs()
// {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_MULTI_PROCESS);
// } else {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_PRIVATE);
// }
// }
//
// public static DataManager.Language getLanguage() {
// final Locale locale = getContext().getResources().getConfiguration().locale;
// final String lang = locale.getLanguage();
// if("en".equals(lang)){ return DataManager.Language.ENGLISH;}
// if("fr".equals(lang)){ return DataManager.Language.FRENCH;}
// /* default choice is dutch */
// return DataManager.Language.DUTCH;
// }
//
// public static void saveLanguage(DataManager.Language lang){
// String lng = "nl";//default dutch
// if(lang == DataManager.Language.ENGLISH){lng="en";}
// if(lang == DataManager.Language.FRENCH){lng ="fr";}
// getPrefs().edit().putString(ARG_LANG,lng).apply();
// }
//
// public static void loadLanguage(Context context){
// final String lang = getPrefs().getString(ARG_LANG,"nl");/*Default dutch*/
// final Locale locale = new Locale(lang);
// LanguageChoiceActivity.setLang(locale,context);
// }
//
// public static List<POI> getSavedRoute(){
// final String poiIds = getPrefs().getString(ARG_ROUTE,"");
// final List<POI> toReturn = new ArrayList<POI>();
// if(!poiIds.equals("")){
// final String[] splitted = poiIds.split(",");
// for(String s: splitted){
// try {
// final int id = Integer.parseInt(s);
// final POI toAdd = DataManager.getPOIbyID(id);
// toReturn.add(toAdd);
// }catch(Exception ex){
// //can't parse string to int ....
// }
// }
// }
// return toReturn;
// }
//
// public static void saveRoute(List<POI> route){
// final StringBuilder sb = new StringBuilder();
// for(POI poi : route){
// sb.append(poi.id);
// sb.append(",");
// }
// if(sb.length() > 0) {
// sb.delete(sb.length() - 1, sb.length());
// }
// getPrefs().edit().putString(ARG_ROUTE,sb.toString()).apply();
// }
//
// public static void setPanoramaNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_PANORAMA_TIME, false)
// .apply();
// }
// public static boolean isFirstPanoramaTime() {
// return getPrefs().getBoolean(ARG_FIRS_PANORAMA_TIME, true);
// }
//
// }
// Path: app/src/main/java/be/artoria/belfortapp/activities/BaseActivity.java
import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.ViewGroup;
import android.view.Window;
import be.artoria.belfortapp.R;
import be.artoria.belfortapp.app.PrefUtils;
package be.artoria.belfortapp.activities;
public class BaseActivity extends ActionBarActivity {
protected static Typeface athelas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar ab = getActionBar();
if(ab != null ) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color2)));
} | PrefUtils.loadLanguage(this); |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/app/DataManager.java | // Path: app/src/main/java/be/artoria/belfortapp/sql/POIDAO.java
// public class POIDAO {
//
// // Database fields
// private SQLiteDatabase database;
// private final POIDbHelper dbHelper;
// private static final String[] allColumns = {
// POIEntry.COLUMN_NAME_ENTRY_ID ,
// POIEntry.COLUMN_NAME_NAME ,
// POIEntry.COLUMN_NAME_NAME_EN ,
// POIEntry.COLUMN_NAME_NAME_FR ,
// POIEntry.COLUMN_NAME_LAT ,
// POIEntry.COLUMN_NAME_LON ,
// POIEntry.COLUMN_NAME_HEIGHT ,
// POIEntry.COLUMN_NAME_DESCRIPTION ,
// POIEntry.COLUMN_NAME_DESCRIPTION_EN ,
// POIEntry.COLUMN_NAME_DESCRIPTION_FR ,
// POIEntry.COLUMN_NAME_IMAGE_URL,
// POIEntry.COLUMN_NAME_TYPE
// };
//
// public POIDAO(Context context) {
// dbHelper = new POIDbHelper(context);
// }
//
// public void open() throws SQLException {
// database = dbHelper.getWritableDatabase();
// }
//
// public void close() {
// dbHelper.close();
// }
//
// public POI savePOI(POI poi) {
// final ContentValues values = new ContentValues();
//
// values.put(POIEntry.COLUMN_NAME_ENTRY_ID, poi.id);
// values.put(POIEntry.COLUMN_NAME_NAME, poi.NL_name);
// values.put(POIEntry.COLUMN_NAME_NAME_EN, poi.ENG_name);
// values.put(POIEntry.COLUMN_NAME_NAME_FR, poi.FR_name);
// values.put(POIEntry.COLUMN_NAME_LAT, poi.lat);
// values.put(POIEntry.COLUMN_NAME_LON, poi.lon);
// values.put(POIEntry.COLUMN_NAME_HEIGHT, poi.height);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION, poi.NL_description);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION_EN, poi.ENG_description);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION_FR, poi.FR_description);
// values.put(POIEntry.COLUMN_NAME_IMAGE_URL, poi.image_link);
// values.put(POIEntry.COLUMN_NAME_TYPE,poi.type);
//
// database.insert(POIEntry.TABLE_NAME, null,
// values);
//
// return poi;
// }
//
// public void clearTable(){
// database.execSQL(POIDbHelper.SQL_DELETE_ENTRIES);
// database.execSQL(POIDbHelper.SQL_CREATE_ENTRIES);
// }
//
// public List<POI> getAllPOIs() {
// final List<POI> pois = new ArrayList<POI>();
//
// final Cursor cursor = database.query(POIEntry.TABLE_NAME,
// allColumns, null, null, null, null, null);
//
// cursor.moveToFirst();
// while (!cursor.isAfterLast()) {
// final POI poi = cursorToPOI(cursor);
// pois.add(poi);
// cursor.moveToNext();
// }
// // make sure to close the cursor
// cursor.close();
// return pois;
// }
//
// private POI cursorToPOI(Cursor cursor) {
// if(cursor == null ) return null;
// POI poi = new POI();
// poi.id = cursor.getInt(cursor.getColumnIndex(POIEntry.COLUMN_NAME_ENTRY_ID));
// poi.NL_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME));
// poi.ENG_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME_EN));
// poi.FR_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME_FR));
// poi.lat = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_LAT));
// poi.lon = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_LON));
// poi.height = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_HEIGHT));
// poi.NL_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION));
// poi.ENG_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION_EN));
// poi.FR_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION_FR));
// poi.image_link = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_IMAGE_URL));
// poi.type = Integer.parseInt(cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_TYPE)));
// return poi;
// }
// }
| import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import be.artoria.belfortapp.sql.POIDAO; | package be.artoria.belfortapp.app;
/**
* Created by Laurens on 01/07/2014.
*/
public class DataManager {
public static int numberOfPOIs = 0;
/* Check if the data should be refreshed after a resume or whatever,
* make sure the data exists is reasonably fresh.
*/
public static void refresh() {
// TODO implement
}
public enum Language{
DUTCH,ENGLISH,FRENCH
}
public static Language lang = null;
private static final DataManager INSTANCE = new DataManager();
private static final List<POI> poiList = new ArrayList<POI>(); | // Path: app/src/main/java/be/artoria/belfortapp/sql/POIDAO.java
// public class POIDAO {
//
// // Database fields
// private SQLiteDatabase database;
// private final POIDbHelper dbHelper;
// private static final String[] allColumns = {
// POIEntry.COLUMN_NAME_ENTRY_ID ,
// POIEntry.COLUMN_NAME_NAME ,
// POIEntry.COLUMN_NAME_NAME_EN ,
// POIEntry.COLUMN_NAME_NAME_FR ,
// POIEntry.COLUMN_NAME_LAT ,
// POIEntry.COLUMN_NAME_LON ,
// POIEntry.COLUMN_NAME_HEIGHT ,
// POIEntry.COLUMN_NAME_DESCRIPTION ,
// POIEntry.COLUMN_NAME_DESCRIPTION_EN ,
// POIEntry.COLUMN_NAME_DESCRIPTION_FR ,
// POIEntry.COLUMN_NAME_IMAGE_URL,
// POIEntry.COLUMN_NAME_TYPE
// };
//
// public POIDAO(Context context) {
// dbHelper = new POIDbHelper(context);
// }
//
// public void open() throws SQLException {
// database = dbHelper.getWritableDatabase();
// }
//
// public void close() {
// dbHelper.close();
// }
//
// public POI savePOI(POI poi) {
// final ContentValues values = new ContentValues();
//
// values.put(POIEntry.COLUMN_NAME_ENTRY_ID, poi.id);
// values.put(POIEntry.COLUMN_NAME_NAME, poi.NL_name);
// values.put(POIEntry.COLUMN_NAME_NAME_EN, poi.ENG_name);
// values.put(POIEntry.COLUMN_NAME_NAME_FR, poi.FR_name);
// values.put(POIEntry.COLUMN_NAME_LAT, poi.lat);
// values.put(POIEntry.COLUMN_NAME_LON, poi.lon);
// values.put(POIEntry.COLUMN_NAME_HEIGHT, poi.height);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION, poi.NL_description);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION_EN, poi.ENG_description);
// values.put(POIEntry.COLUMN_NAME_DESCRIPTION_FR, poi.FR_description);
// values.put(POIEntry.COLUMN_NAME_IMAGE_URL, poi.image_link);
// values.put(POIEntry.COLUMN_NAME_TYPE,poi.type);
//
// database.insert(POIEntry.TABLE_NAME, null,
// values);
//
// return poi;
// }
//
// public void clearTable(){
// database.execSQL(POIDbHelper.SQL_DELETE_ENTRIES);
// database.execSQL(POIDbHelper.SQL_CREATE_ENTRIES);
// }
//
// public List<POI> getAllPOIs() {
// final List<POI> pois = new ArrayList<POI>();
//
// final Cursor cursor = database.query(POIEntry.TABLE_NAME,
// allColumns, null, null, null, null, null);
//
// cursor.moveToFirst();
// while (!cursor.isAfterLast()) {
// final POI poi = cursorToPOI(cursor);
// pois.add(poi);
// cursor.moveToNext();
// }
// // make sure to close the cursor
// cursor.close();
// return pois;
// }
//
// private POI cursorToPOI(Cursor cursor) {
// if(cursor == null ) return null;
// POI poi = new POI();
// poi.id = cursor.getInt(cursor.getColumnIndex(POIEntry.COLUMN_NAME_ENTRY_ID));
// poi.NL_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME));
// poi.ENG_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME_EN));
// poi.FR_name = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_NAME_FR));
// poi.lat = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_LAT));
// poi.lon = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_LON));
// poi.height = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_HEIGHT));
// poi.NL_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION));
// poi.ENG_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION_EN));
// poi.FR_description = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_DESCRIPTION_FR));
// poi.image_link = cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_IMAGE_URL));
// poi.type = Integer.parseInt(cursor.getString(cursor.getColumnIndex(POIEntry.COLUMN_NAME_TYPE)));
// return poi;
// }
// }
// Path: app/src/main/java/be/artoria/belfortapp/app/DataManager.java
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import be.artoria.belfortapp.sql.POIDAO;
package be.artoria.belfortapp.app;
/**
* Created by Laurens on 01/07/2014.
*/
public class DataManager {
public static int numberOfPOIs = 0;
/* Check if the data should be refreshed after a resume or whatever,
* make sure the data exists is reasonably fresh.
*/
public static void refresh() {
// TODO implement
}
public enum Language{
DUTCH,ENGLISH,FRENCH
}
public static Language lang = null;
private static final DataManager INSTANCE = new DataManager();
private static final List<POI> poiList = new ArrayList<POI>(); | public static final POIDAO poidao = new POIDAO(PrefUtils.getContext()); |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/activities/LaunchActivity.java | // Path: app/src/main/java/be/artoria/belfortapp/app/PrefUtils.java
// public class PrefUtils {
// public static final String TAG = "Belfort";
// public static final String DATASET_URL = "https://raw.githubusercontent.com/oSoc14/ArtoriaData/master/poi.json";
//
// private static final String ARG_USER_KEY = "be.artoria.belfort";
// private static final String ARG_DOWNLOAD = "be.artoria.belfort.downloadtimes";
// private static final String ARG_FIRS_TTIME = "be.artoria.belfort.firstTime";
// private static final String ARG_ROUTE = "be.artoria.belfort.route";
// private static final String ARG_LANG = "be.artoria.belfort.lang";
// private static final String ARG_FIRS_PANORAMA_TIME = "be.artoria.belfort.panorama_firstTime";
//
// private static Context CONTEXT;
//
// public static Context getContext()
// {
// return CONTEXT;
// }
//
// public static void initialize(Application application)
// {
// CONTEXT = application;
// }
//
// public static void saveTimeStampDownloads()
// {
// getPrefs()
// .edit()
// .putLong(ARG_DOWNLOAD, System.currentTimeMillis())
// .apply();
// }
//
// public static boolean isFirstTime() {
// return getPrefs().getBoolean(ARG_FIRS_TTIME, true);
// }
//
// public static void setNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_TTIME, false)
// .apply();
// }
//
// public static long getTimeStampDownloads()
// {
// return getPrefs().getLong(ARG_DOWNLOAD, 0);
// }
//
// public static void removeAll()
// {
// getPrefs().edit().clear().apply();
// }
//
// // get preferences
// @SuppressWarnings("NewApi")
// private static SharedPreferences getPrefs()
// {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_MULTI_PROCESS);
// } else {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_PRIVATE);
// }
// }
//
// public static DataManager.Language getLanguage() {
// final Locale locale = getContext().getResources().getConfiguration().locale;
// final String lang = locale.getLanguage();
// if("en".equals(lang)){ return DataManager.Language.ENGLISH;}
// if("fr".equals(lang)){ return DataManager.Language.FRENCH;}
// /* default choice is dutch */
// return DataManager.Language.DUTCH;
// }
//
// public static void saveLanguage(DataManager.Language lang){
// String lng = "nl";//default dutch
// if(lang == DataManager.Language.ENGLISH){lng="en";}
// if(lang == DataManager.Language.FRENCH){lng ="fr";}
// getPrefs().edit().putString(ARG_LANG,lng).apply();
// }
//
// public static void loadLanguage(Context context){
// final String lang = getPrefs().getString(ARG_LANG,"nl");/*Default dutch*/
// final Locale locale = new Locale(lang);
// LanguageChoiceActivity.setLang(locale,context);
// }
//
// public static List<POI> getSavedRoute(){
// final String poiIds = getPrefs().getString(ARG_ROUTE,"");
// final List<POI> toReturn = new ArrayList<POI>();
// if(!poiIds.equals("")){
// final String[] splitted = poiIds.split(",");
// for(String s: splitted){
// try {
// final int id = Integer.parseInt(s);
// final POI toAdd = DataManager.getPOIbyID(id);
// toReturn.add(toAdd);
// }catch(Exception ex){
// //can't parse string to int ....
// }
// }
// }
// return toReturn;
// }
//
// public static void saveRoute(List<POI> route){
// final StringBuilder sb = new StringBuilder();
// for(POI poi : route){
// sb.append(poi.id);
// sb.append(",");
// }
// if(sb.length() > 0) {
// sb.delete(sb.length() - 1, sb.length());
// }
// getPrefs().edit().putString(ARG_ROUTE,sb.toString()).apply();
// }
//
// public static void setPanoramaNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_PANORAMA_TIME, false)
// .apply();
// }
// public static boolean isFirstPanoramaTime() {
// return getPrefs().getBoolean(ARG_FIRS_PANORAMA_TIME, true);
// }
//
// }
| import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import be.artoria.belfortapp.R;
import be.artoria.belfortapp.app.PrefUtils; | package be.artoria.belfortapp.activities;
public class LaunchActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent nextPage; | // Path: app/src/main/java/be/artoria/belfortapp/app/PrefUtils.java
// public class PrefUtils {
// public static final String TAG = "Belfort";
// public static final String DATASET_URL = "https://raw.githubusercontent.com/oSoc14/ArtoriaData/master/poi.json";
//
// private static final String ARG_USER_KEY = "be.artoria.belfort";
// private static final String ARG_DOWNLOAD = "be.artoria.belfort.downloadtimes";
// private static final String ARG_FIRS_TTIME = "be.artoria.belfort.firstTime";
// private static final String ARG_ROUTE = "be.artoria.belfort.route";
// private static final String ARG_LANG = "be.artoria.belfort.lang";
// private static final String ARG_FIRS_PANORAMA_TIME = "be.artoria.belfort.panorama_firstTime";
//
// private static Context CONTEXT;
//
// public static Context getContext()
// {
// return CONTEXT;
// }
//
// public static void initialize(Application application)
// {
// CONTEXT = application;
// }
//
// public static void saveTimeStampDownloads()
// {
// getPrefs()
// .edit()
// .putLong(ARG_DOWNLOAD, System.currentTimeMillis())
// .apply();
// }
//
// public static boolean isFirstTime() {
// return getPrefs().getBoolean(ARG_FIRS_TTIME, true);
// }
//
// public static void setNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_TTIME, false)
// .apply();
// }
//
// public static long getTimeStampDownloads()
// {
// return getPrefs().getLong(ARG_DOWNLOAD, 0);
// }
//
// public static void removeAll()
// {
// getPrefs().edit().clear().apply();
// }
//
// // get preferences
// @SuppressWarnings("NewApi")
// private static SharedPreferences getPrefs()
// {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_MULTI_PROCESS);
// } else {
// return CONTEXT.getSharedPreferences(ARG_USER_KEY, Context.MODE_PRIVATE);
// }
// }
//
// public static DataManager.Language getLanguage() {
// final Locale locale = getContext().getResources().getConfiguration().locale;
// final String lang = locale.getLanguage();
// if("en".equals(lang)){ return DataManager.Language.ENGLISH;}
// if("fr".equals(lang)){ return DataManager.Language.FRENCH;}
// /* default choice is dutch */
// return DataManager.Language.DUTCH;
// }
//
// public static void saveLanguage(DataManager.Language lang){
// String lng = "nl";//default dutch
// if(lang == DataManager.Language.ENGLISH){lng="en";}
// if(lang == DataManager.Language.FRENCH){lng ="fr";}
// getPrefs().edit().putString(ARG_LANG,lng).apply();
// }
//
// public static void loadLanguage(Context context){
// final String lang = getPrefs().getString(ARG_LANG,"nl");/*Default dutch*/
// final Locale locale = new Locale(lang);
// LanguageChoiceActivity.setLang(locale,context);
// }
//
// public static List<POI> getSavedRoute(){
// final String poiIds = getPrefs().getString(ARG_ROUTE,"");
// final List<POI> toReturn = new ArrayList<POI>();
// if(!poiIds.equals("")){
// final String[] splitted = poiIds.split(",");
// for(String s: splitted){
// try {
// final int id = Integer.parseInt(s);
// final POI toAdd = DataManager.getPOIbyID(id);
// toReturn.add(toAdd);
// }catch(Exception ex){
// //can't parse string to int ....
// }
// }
// }
// return toReturn;
// }
//
// public static void saveRoute(List<POI> route){
// final StringBuilder sb = new StringBuilder();
// for(POI poi : route){
// sb.append(poi.id);
// sb.append(",");
// }
// if(sb.length() > 0) {
// sb.delete(sb.length() - 1, sb.length());
// }
// getPrefs().edit().putString(ARG_ROUTE,sb.toString()).apply();
// }
//
// public static void setPanoramaNotFirstTime() {
// getPrefs()
// .edit()
// .putBoolean(ARG_FIRS_PANORAMA_TIME, false)
// .apply();
// }
// public static boolean isFirstPanoramaTime() {
// return getPrefs().getBoolean(ARG_FIRS_PANORAMA_TIME, true);
// }
//
// }
// Path: app/src/main/java/be/artoria/belfortapp/activities/LaunchActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import be.artoria.belfortapp.R;
import be.artoria.belfortapp.app.PrefUtils;
package be.artoria.belfortapp.activities;
public class LaunchActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent nextPage; | if(PrefUtils.isFirstTime()){ |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/mixare/mgr/datasource/DataSourceManager.java | // Path: app/src/main/java/be/artoria/belfortapp/mixare/data/DataSource.java
// public class DataSource {
//
// private static final String name = "Artoria";
//
// public enum TYPE {
// WIKIPEDIA, BUZZ, TWITTER, OSM, MIXARE, ARTORIA
// };
//
// private static final TYPE type = TYPE.ARTORIA;
//
//
// public DataSource() {
// }
//
// public int getColor() {
// return Color.RED;
// }
//
//
// public TYPE getType() {
// return this.type;
// }
//
// public String getName() {
// return this.name;
// }
//
// @Override
// public String toString() {
// return "ARTORIA DataSource ";
// }
// }
| import be.artoria.belfortapp.mixare.data.DataSource; | /*
* Copyleft 2012 - Peer internet solutions & Alessandro Staniscia
*
* This file is part of be.artoria.belfortapp.mixare.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package be.artoria.belfortapp.mixare.mgr.datasource;
/**
* This class is responsible for Data Source Managing
*
*/
public interface DataSourceManager {
/**
* Sync DataSouceManager with DataSourceStorage.
*/
void refreshDataSources();
/**
* Clean all old datasource and insert only source.
*
* @param source
*/ | // Path: app/src/main/java/be/artoria/belfortapp/mixare/data/DataSource.java
// public class DataSource {
//
// private static final String name = "Artoria";
//
// public enum TYPE {
// WIKIPEDIA, BUZZ, TWITTER, OSM, MIXARE, ARTORIA
// };
//
// private static final TYPE type = TYPE.ARTORIA;
//
//
// public DataSource() {
// }
//
// public int getColor() {
// return Color.RED;
// }
//
//
// public TYPE getType() {
// return this.type;
// }
//
// public String getName() {
// return this.name;
// }
//
// @Override
// public String toString() {
// return "ARTORIA DataSource ";
// }
// }
// Path: app/src/main/java/be/artoria/belfortapp/mixare/mgr/datasource/DataSourceManager.java
import be.artoria.belfortapp.mixare.data.DataSource;
/*
* Copyleft 2012 - Peer internet solutions & Alessandro Staniscia
*
* This file is part of be.artoria.belfortapp.mixare.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package be.artoria.belfortapp.mixare.mgr.datasource;
/**
* This class is responsible for Data Source Managing
*
*/
public interface DataSourceManager {
/**
* Sync DataSouceManager with DataSourceStorage.
*/
void refreshDataSources();
/**
* Clean all old datasource and insert only source.
*
* @param source
*/ | void setAllDataSourcesforLauncher(DataSource source); |
oSoc14/Artoria | app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/InitialMarkerData.java | // Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/ParcelableProperty.java
// public class ParcelableProperty implements Parcelable {
//
// private String className;
// private Parcelable object;
//
// public ParcelableProperty(String className, Parcelable object) {
// this.className = className;
// this.object = object;
// }
//
// public static final Parcelable.Creator<ParcelableProperty> CREATOR = new Parcelable.Creator<ParcelableProperty>() {
// public ParcelableProperty createFromParcel(Parcel in) {
// return new ParcelableProperty(in);
// }
//
// public ParcelableProperty[] newArray(int size) {
// return new ParcelableProperty[size];
// }
// };
//
// private ParcelableProperty(Parcel in) {
// className = in.readString();
// object = in.readParcelable(getClassLoader());
// }
//
// public ClassLoader getClassLoader() {
// try {
// return Class.forName(className).getClassLoader();
// } catch (ClassNotFoundException e) {
// throw new RuntimeException();
// }
// }
//
// public Parcelable getObject() {
// return object;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(className);
// dest.writeParcelable(object, 0);
// }
//
// }
//
// Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/PrimitiveProperty.java
// public class PrimitiveProperty implements Parcelable {
//
// private String primitivename;
// private Object object;
//
// public enum primitive {
// STRING, INT, DOUBLE, FLOAT, LONG, BYTE;
// }
//
// public PrimitiveProperty(String primitivename, Object object) {
// this.primitivename = primitivename;
// this.object = object;
// }
//
// public PrimitiveProperty(Parcel in) {
// primitivename = in.readString();
// if (primitivename.equals(primitive.STRING.name())) {
// object = in.readString();
// }
// else if (primitivename.equals(primitive.INT.name())) {
// object = in.readInt();
// }
// else if (primitivename.equals(primitive.DOUBLE.name())) {
// object = in.readDouble();
// }
// else if (primitivename.equals(primitive.FLOAT.name())) {
// object = in.readFloat();
// }
// else if (primitivename.equals(primitive.LONG.name())) {
// object = in.readLong();
// }
// else if (primitivename.equals(primitive.BYTE.name())) {
// in.readByteArray((byte[])object);
// }
// }
//
// public static final Parcelable.Creator<PrimitiveProperty> CREATOR = new Parcelable.Creator<PrimitiveProperty>() {
// public PrimitiveProperty createFromParcel(Parcel in) {
// return new PrimitiveProperty(in);
// }
//
// public PrimitiveProperty[] newArray(int size) {
// return new PrimitiveProperty[size];
// }
// };
//
// public Object getObject() {
// return object;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(primitivename);
// if (primitivename.equals(primitive.STRING.name())) {
// dest.writeString((String)object);
// }
// else if (primitivename.equals(primitive.INT.name())) {
// dest.writeInt((Integer)object);
// }
// else if (primitivename.equals(primitive.DOUBLE.name())) {
// dest.writeDouble((Double)object);
// }
// else if (primitivename.equals(primitive.FLOAT.name())) {
// dest.writeFloat((Float)object);
// }
// else if (primitivename.equals(primitive.LONG.name())) {
// dest.writeLong((Long)object);
// }
// else if (primitivename.equals(primitive.BYTE.name())) {
// dest.writeByteArray((byte[])object);
// }
// }
//
// }
//
// Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/PrimitiveProperty.java
// public enum primitive {
// STRING, INT, DOUBLE, FLOAT, LONG, BYTE;
// }
| import java.util.HashMap;
import java.util.Map;
import be.artoria.belfortapp.mixare.lib.marker.draw.ParcelableProperty;
import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty;
import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty.primitive;
import android.os.Parcel;
import android.os.Parcelable; | constr[3] = longitude;
constr[4] = altitude;
constr[5] = link;
constr[6] = type;
constr[7] = colour;
}
public InitialMarkerData(Parcel in) {
readParcel(in);
}
public void setMarkerName(String markerName) {
this.markerName = markerName;
}
public String getMarkerName() {
return markerName;
}
public static final Parcelable.Creator<InitialMarkerData> CREATOR = new Parcelable.Creator<InitialMarkerData>() {
public InitialMarkerData createFromParcel(Parcel in) {
return new InitialMarkerData(in);
}
public InitialMarkerData[] newArray(int size) {
return new InitialMarkerData[size];
}
};
public void setExtras(String name, int value){ | // Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/ParcelableProperty.java
// public class ParcelableProperty implements Parcelable {
//
// private String className;
// private Parcelable object;
//
// public ParcelableProperty(String className, Parcelable object) {
// this.className = className;
// this.object = object;
// }
//
// public static final Parcelable.Creator<ParcelableProperty> CREATOR = new Parcelable.Creator<ParcelableProperty>() {
// public ParcelableProperty createFromParcel(Parcel in) {
// return new ParcelableProperty(in);
// }
//
// public ParcelableProperty[] newArray(int size) {
// return new ParcelableProperty[size];
// }
// };
//
// private ParcelableProperty(Parcel in) {
// className = in.readString();
// object = in.readParcelable(getClassLoader());
// }
//
// public ClassLoader getClassLoader() {
// try {
// return Class.forName(className).getClassLoader();
// } catch (ClassNotFoundException e) {
// throw new RuntimeException();
// }
// }
//
// public Parcelable getObject() {
// return object;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(className);
// dest.writeParcelable(object, 0);
// }
//
// }
//
// Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/PrimitiveProperty.java
// public class PrimitiveProperty implements Parcelable {
//
// private String primitivename;
// private Object object;
//
// public enum primitive {
// STRING, INT, DOUBLE, FLOAT, LONG, BYTE;
// }
//
// public PrimitiveProperty(String primitivename, Object object) {
// this.primitivename = primitivename;
// this.object = object;
// }
//
// public PrimitiveProperty(Parcel in) {
// primitivename = in.readString();
// if (primitivename.equals(primitive.STRING.name())) {
// object = in.readString();
// }
// else if (primitivename.equals(primitive.INT.name())) {
// object = in.readInt();
// }
// else if (primitivename.equals(primitive.DOUBLE.name())) {
// object = in.readDouble();
// }
// else if (primitivename.equals(primitive.FLOAT.name())) {
// object = in.readFloat();
// }
// else if (primitivename.equals(primitive.LONG.name())) {
// object = in.readLong();
// }
// else if (primitivename.equals(primitive.BYTE.name())) {
// in.readByteArray((byte[])object);
// }
// }
//
// public static final Parcelable.Creator<PrimitiveProperty> CREATOR = new Parcelable.Creator<PrimitiveProperty>() {
// public PrimitiveProperty createFromParcel(Parcel in) {
// return new PrimitiveProperty(in);
// }
//
// public PrimitiveProperty[] newArray(int size) {
// return new PrimitiveProperty[size];
// }
// };
//
// public Object getObject() {
// return object;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(primitivename);
// if (primitivename.equals(primitive.STRING.name())) {
// dest.writeString((String)object);
// }
// else if (primitivename.equals(primitive.INT.name())) {
// dest.writeInt((Integer)object);
// }
// else if (primitivename.equals(primitive.DOUBLE.name())) {
// dest.writeDouble((Double)object);
// }
// else if (primitivename.equals(primitive.FLOAT.name())) {
// dest.writeFloat((Float)object);
// }
// else if (primitivename.equals(primitive.LONG.name())) {
// dest.writeLong((Long)object);
// }
// else if (primitivename.equals(primitive.BYTE.name())) {
// dest.writeByteArray((byte[])object);
// }
// }
//
// }
//
// Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/draw/PrimitiveProperty.java
// public enum primitive {
// STRING, INT, DOUBLE, FLOAT, LONG, BYTE;
// }
// Path: app/src/main/java/be/artoria/belfortapp/mixare/lib/marker/InitialMarkerData.java
import java.util.HashMap;
import java.util.Map;
import be.artoria.belfortapp.mixare.lib.marker.draw.ParcelableProperty;
import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty;
import be.artoria.belfortapp.mixare.lib.marker.draw.PrimitiveProperty.primitive;
import android.os.Parcel;
import android.os.Parcelable;
constr[3] = longitude;
constr[4] = altitude;
constr[5] = link;
constr[6] = type;
constr[7] = colour;
}
public InitialMarkerData(Parcel in) {
readParcel(in);
}
public void setMarkerName(String markerName) {
this.markerName = markerName;
}
public String getMarkerName() {
return markerName;
}
public static final Parcelable.Creator<InitialMarkerData> CREATOR = new Parcelable.Creator<InitialMarkerData>() {
public InitialMarkerData createFromParcel(Parcel in) {
return new InitialMarkerData(in);
}
public InitialMarkerData[] newArray(int size) {
return new InitialMarkerData[size];
}
};
public void setExtras(String name, int value){ | extraPrimitives.put(name, new PrimitiveProperty(primitive.INT.name(), value)); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/serializer/TableSerializer.java | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
| import java.io.IOException;
import java.util.List;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider; | package org.cytoscape.rest.internal.serializer;
public class TableSerializer extends JsonSerializer<CyTable> {
@Override
public Class<CyTable> handledType() {
return CyTable.class;
}
@Override
public void serialize(CyTable table, JsonGenerator generator, SerializerProvider provider) throws IOException,
JsonProcessingException {
generator.useDefaultPrettyPrinter();
generator.writeStartObject();
generator.writeNumberField(CyIdentifiable.SUID, table.getSUID()); | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/serializer/TableSerializer.java
import java.io.IOException;
import java.util.List;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
package org.cytoscape.rest.internal.serializer;
public class TableSerializer extends JsonSerializer<CyTable> {
@Override
public Class<CyTable> handledType() {
return CyTable.class;
}
@Override
public void serialize(CyTable table, JsonGenerator generator, SerializerProvider provider) throws IOException,
JsonProcessingException {
generator.useDefaultPrettyPrinter();
generator.writeStartObject();
generator.writeNumberField(CyIdentifiable.SUID, table.getSUID()); | generator.writeStringField(JsonTags.TITLE, table.getTitle()); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/SessionResource.java | // Path: src/main/java/org/cytoscape/rest/internal/task/HeadlessTaskMonitor.java
// public class HeadlessTaskMonitor implements TaskMonitor {
//
// private static final Logger logger = LoggerFactory.getLogger(HeadlessTaskMonitor.class);
//
// private String taskName = "";
//
// public void setTask(final Task task) {
// this.taskName = "Task (" + task.toString() + ")";
// }
//
//
// @Override
// public void setTitle(final String title) {
// logger.info(taskName + " title: " + title);
// }
//
//
// @Override
// public void setStatusMessage(final String statusMessage) {
// logger.info(taskName + " status: " + statusMessage);
// }
//
//
// @Override
// public void setProgress(final double progress) {
// }
//
//
// @Override
// public void showMessage(Level level, String message) {
// }
// }
| import java.io.File;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.rest.internal.task.HeadlessTaskMonitor;
import org.cytoscape.session.CySessionManager;
import org.cytoscape.task.create.NewSessionTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.write.SaveSessionAsTaskFactory;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator; | */
@GET
@Path("/name")
@Produces(MediaType.APPLICATION_JSON)
public String getSessionName() {
String sessionName = sessionManager.getCurrentSessionFileName();
if(sessionName == null || sessionName.isEmpty()) {
sessionName = "";
}
return "{\"name\": \"" + sessionName +"\"}";
}
/**
*
* @summary Delete current session and start new one
*
* @return Success message
*
*/
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String deleteSession() {
try {
TaskIterator itr = newSessionTaskFactory.createTaskIterator(true);
while(itr.hasNext()) {
final Task task = itr.next(); | // Path: src/main/java/org/cytoscape/rest/internal/task/HeadlessTaskMonitor.java
// public class HeadlessTaskMonitor implements TaskMonitor {
//
// private static final Logger logger = LoggerFactory.getLogger(HeadlessTaskMonitor.class);
//
// private String taskName = "";
//
// public void setTask(final Task task) {
// this.taskName = "Task (" + task.toString() + ")";
// }
//
//
// @Override
// public void setTitle(final String title) {
// logger.info(taskName + " title: " + title);
// }
//
//
// @Override
// public void setStatusMessage(final String statusMessage) {
// logger.info(taskName + " status: " + statusMessage);
// }
//
//
// @Override
// public void setProgress(final double progress) {
// }
//
//
// @Override
// public void showMessage(Level level, String message) {
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/SessionResource.java
import java.io.File;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.rest.internal.task.HeadlessTaskMonitor;
import org.cytoscape.session.CySessionManager;
import org.cytoscape.task.create.NewSessionTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.write.SaveSessionAsTaskFactory;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator;
*/
@GET
@Path("/name")
@Produces(MediaType.APPLICATION_JSON)
public String getSessionName() {
String sessionName = sessionManager.getCurrentSessionFileName();
if(sessionName == null || sessionName.isEmpty()) {
sessionName = "";
}
return "{\"name\": \"" + sessionName +"\"}";
}
/**
*
* @summary Delete current session and start new one
*
* @return Success message
*
*/
@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String deleteSession() {
try {
TaskIterator itr = newSessionTaskFactory.createTaskIterator(true);
while(itr.hasNext()) {
final Task task = itr.next(); | task.run(new HeadlessTaskMonitor()); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/datamapper/TableMapper.java | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.NotFoundException;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.databind.JsonNode; | package org.cytoscape.rest.internal.datamapper;
/**
* Create & Update table objects.
*
*
*/
public class TableMapper {
public void updateColumnName(final JsonNode rootNode, final CyTable table) { | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/TableMapper.java
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.NotFoundException;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.databind.JsonNode;
package org.cytoscape.rest.internal.datamapper;
/**
* Create & Update table objects.
*
*
*/
public class TableMapper {
public void updateColumnName(final JsonNode rootNode, final CyTable table) { | final JsonNode currentNameTag = rootNode.get(JsonTags.COLUMN_NAME_OLD); |
idekerlab/cyREST | src/test/java/org/cytoscape/rest/service/SessionResourceTest.java | // Path: src/main/java/org/cytoscape/rest/internal/resource/SessionResource.java
// @Singleton
// @Path("/v1/session")
// public class SessionResource extends AbstractResource {
//
// @Context
// @NotNull
// private CySessionManager sessionManager;
//
// @Context
// @NotNull
// private SaveSessionAsTaskFactory saveSessionAsTaskFactory;
//
// @Context
// @NotNull
// private OpenSessionTaskFactory openSessionTaskFactory;
//
// @Context
// @NotNull
// private NewSessionTaskFactory newSessionTaskFactory;
//
//
// public SessionResource() {
// super();
// }
//
//
// /**
// *
// * @summary Get current session name
// *
// * @return Current session name
// */
// @GET
// @Path("/name")
// @Produces(MediaType.APPLICATION_JSON)
// public String getSessionName() {
// String sessionName = sessionManager.getCurrentSessionFileName();
// if(sessionName == null || sessionName.isEmpty()) {
// sessionName = "";
// }
//
// return "{\"name\": \"" + sessionName +"\"}";
// }
//
//
// /**
// *
// * @summary Delete current session and start new one
// *
// * @return Success message
// *
// */
// @DELETE
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String deleteSession() {
//
// try {
// TaskIterator itr = newSessionTaskFactory.createTaskIterator(true);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not delete current session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// return "{\"message\": \"New session created.\"}";
// }
//
//
// /**
// * This get method load a new session from a file
// *
// * @summary Load new session from a local file
// *
// * @param file File name (should be absolute path)
// *
// * @return Session file name as string
// *
// */
// @GET
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String getSessionFromFile(@QueryParam("file") String file) {
// File sessionFile = null;
// try {
// sessionFile = new File(file);
// TaskIterator itr = openSessionTaskFactory.createTaskIterator(sessionFile);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
//
// return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}";
// }
//
//
// /**
// *
// * @summary Create a session file
// *
// * @param file Session file location (should be absolute path)
// *
// * @return Session file name
// */
// @POST
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String createSessionFile(@QueryParam("file") String file) {
// File sessionFile = null;
// try {
// sessionFile = new File(file);
// TaskIterator itr = saveSessionAsTaskFactory.createTaskIterator(sessionFile);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
//
// return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}";
// }
// }
| import static org.junit.Assert.*;
import java.io.File;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.rest.internal.resource.SessionResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.service;
public class SessionResourceTest extends BasicResourceTest {
private ObjectMapper mapper = new ObjectMapper();
@Override
protected Application configure() { | // Path: src/main/java/org/cytoscape/rest/internal/resource/SessionResource.java
// @Singleton
// @Path("/v1/session")
// public class SessionResource extends AbstractResource {
//
// @Context
// @NotNull
// private CySessionManager sessionManager;
//
// @Context
// @NotNull
// private SaveSessionAsTaskFactory saveSessionAsTaskFactory;
//
// @Context
// @NotNull
// private OpenSessionTaskFactory openSessionTaskFactory;
//
// @Context
// @NotNull
// private NewSessionTaskFactory newSessionTaskFactory;
//
//
// public SessionResource() {
// super();
// }
//
//
// /**
// *
// * @summary Get current session name
// *
// * @return Current session name
// */
// @GET
// @Path("/name")
// @Produces(MediaType.APPLICATION_JSON)
// public String getSessionName() {
// String sessionName = sessionManager.getCurrentSessionFileName();
// if(sessionName == null || sessionName.isEmpty()) {
// sessionName = "";
// }
//
// return "{\"name\": \"" + sessionName +"\"}";
// }
//
//
// /**
// *
// * @summary Delete current session and start new one
// *
// * @return Success message
// *
// */
// @DELETE
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String deleteSession() {
//
// try {
// TaskIterator itr = newSessionTaskFactory.createTaskIterator(true);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not delete current session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
// return "{\"message\": \"New session created.\"}";
// }
//
//
// /**
// * This get method load a new session from a file
// *
// * @summary Load new session from a local file
// *
// * @param file File name (should be absolute path)
// *
// * @return Session file name as string
// *
// */
// @GET
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String getSessionFromFile(@QueryParam("file") String file) {
// File sessionFile = null;
// try {
// sessionFile = new File(file);
// TaskIterator itr = openSessionTaskFactory.createTaskIterator(sessionFile);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
//
// return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}";
// }
//
//
// /**
// *
// * @summary Create a session file
// *
// * @param file Session file location (should be absolute path)
// *
// * @return Session file name
// */
// @POST
// @Path("/")
// @Produces(MediaType.APPLICATION_JSON)
// public String createSessionFile(@QueryParam("file") String file) {
// File sessionFile = null;
// try {
// sessionFile = new File(file);
// TaskIterator itr = saveSessionAsTaskFactory.createTaskIterator(sessionFile);
// while(itr.hasNext()) {
// final Task task = itr.next();
// task.run(new HeadlessTaskMonitor());
// }
// } catch (Exception e) {
// e.printStackTrace();
// throw getError("Could not save session.", e, Response.Status.INTERNAL_SERVER_ERROR);
// }
//
// return "{\"file\": \"" + sessionFile.getAbsolutePath() +"\"}";
// }
// }
// Path: src/test/java/org/cytoscape/rest/service/SessionResourceTest.java
import static org.junit.Assert.*;
import java.io.File;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.rest.internal.resource.SessionResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.service;
public class SessionResourceTest extends BasicResourceTest {
private ObjectMapper mapper = new ObjectMapper();
@Override
protected Application configure() { | return new ResourceConfig(SessionResource.class); |
idekerlab/cyREST | src/test/java/org/cytoscape/rest/service/GlobalResourceTest.java | // Path: src/main/java/org/cytoscape/rest/internal/resource/GlobalTableResource.java
// @Singleton
// @Path("/v1/tables")
// public class GlobalTableResource extends AbstractResource {
//
// @Context
// @NotNull
// private CyTableFactory tableFactory;
//
// private final ObjectMapper tableObjectMapper;
//
// public GlobalTableResource() {
// super();
// this.tableObjectMapper = new ObjectMapper();
// this.tableObjectMapper.registerModule(new TableModule());
// }
//
// /**
// *
// * @summary Get number of global tables
// *
// * @return Number of global tables.
// */
// @GET
// @Path("/count")
// @Produces(MediaType.APPLICATION_JSON)
// public String getTableCount() {
// final Set<CyTable> globals = tableManager.getGlobalTables();
// return getNumberObjectString(JsonTags.COUNT, globals.size());
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.ws.rs.core.Application;
import org.cytoscape.rest.internal.resource.GlobalTableResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.service;
public class GlobalResourceTest extends BasicResourceTest {
private ObjectMapper mapper = new ObjectMapper();
@Override
protected Application configure() { | // Path: src/main/java/org/cytoscape/rest/internal/resource/GlobalTableResource.java
// @Singleton
// @Path("/v1/tables")
// public class GlobalTableResource extends AbstractResource {
//
// @Context
// @NotNull
// private CyTableFactory tableFactory;
//
// private final ObjectMapper tableObjectMapper;
//
// public GlobalTableResource() {
// super();
// this.tableObjectMapper = new ObjectMapper();
// this.tableObjectMapper.registerModule(new TableModule());
// }
//
// /**
// *
// * @summary Get number of global tables
// *
// * @return Number of global tables.
// */
// @GET
// @Path("/count")
// @Produces(MediaType.APPLICATION_JSON)
// public String getTableCount() {
// final Set<CyTable> globals = tableManager.getGlobalTables();
// return getNumberObjectString(JsonTags.COUNT, globals.size());
// }
// }
// Path: src/test/java/org/cytoscape/rest/service/GlobalResourceTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.ws.rs.core.Application;
import org.cytoscape.rest.internal.resource.GlobalTableResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.service;
public class GlobalResourceTest extends BasicResourceTest {
private ObjectMapper mapper = new ObjectMapper();
@Override
protected Application configure() { | return new ResourceConfig(GlobalTableResource.class); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/MiscResource.java | // Path: src/main/java/org/cytoscape/rest/internal/model/CytoscapeVersion.java
// @XmlRootElement
// public class CytoscapeVersion {
// private final String apiVersion;
// private final String cytoscapeVersion;
//
// public CytoscapeVersion(final String apiVersion, final String cytoscapeVersion) {
// this.apiVersion = apiVersion;
// this.cytoscapeVersion = cytoscapeVersion;
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @return the cytoscapeVersion
// */
// public String getCytoscapeVersion() {
// return cytoscapeVersion;
// }
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/model/ServerStatus.java
// @XmlRootElement
// public class ServerStatus {
//
// private String apiVersion;
// private Integer numberOfCores;
//
// private MemoryStatus memoryStatus;
//
//
// public ServerStatus() {
// this.setApiVersion("v1");
// this.setNumberOfCores(Runtime.getRuntime().availableProcessors());
// this.setMemoryStatus(new MemoryStatus());
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @param apiVersion
// * the apiVersion to set
// */
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// /**
// * @return the numberOfCores
// */
// public Integer getNumberOfCores() {
// return numberOfCores;
// }
//
// /**
// * @param numberOfCores
// * the numberOfCores to set
// */
// public void setNumberOfCores(Integer numberOfCores) {
// this.numberOfCores = numberOfCores;
// }
//
// /**
// * @return the memoryStatus
// */
// public MemoryStatus getMemoryStatus() {
// return memoryStatus;
// }
//
// /**
// * @param memoryStatus the memoryStatus to set
// */
// public void setMemoryStatus(MemoryStatus memoryStatus) {
// this.memoryStatus = memoryStatus;
// }
//
// }
| import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cytoscape.rest.internal.model.CytoscapeVersion;
import org.cytoscape.rest.internal.model.ServerStatus; | package org.cytoscape.rest.internal.resource;
/**
* Resource to provide general status of the Cytoscape REST server.
*
*
* @servicetag Server status
*
*/
@Singleton
@Path("/v1")
public class MiscResource extends AbstractResource {
/**
* @summary Cytoscape RESTful API server status
*
* @return Summary of server status
*
* @statuscode 500 If REST API Module is not working.
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") | // Path: src/main/java/org/cytoscape/rest/internal/model/CytoscapeVersion.java
// @XmlRootElement
// public class CytoscapeVersion {
// private final String apiVersion;
// private final String cytoscapeVersion;
//
// public CytoscapeVersion(final String apiVersion, final String cytoscapeVersion) {
// this.apiVersion = apiVersion;
// this.cytoscapeVersion = cytoscapeVersion;
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @return the cytoscapeVersion
// */
// public String getCytoscapeVersion() {
// return cytoscapeVersion;
// }
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/model/ServerStatus.java
// @XmlRootElement
// public class ServerStatus {
//
// private String apiVersion;
// private Integer numberOfCores;
//
// private MemoryStatus memoryStatus;
//
//
// public ServerStatus() {
// this.setApiVersion("v1");
// this.setNumberOfCores(Runtime.getRuntime().availableProcessors());
// this.setMemoryStatus(new MemoryStatus());
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @param apiVersion
// * the apiVersion to set
// */
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// /**
// * @return the numberOfCores
// */
// public Integer getNumberOfCores() {
// return numberOfCores;
// }
//
// /**
// * @param numberOfCores
// * the numberOfCores to set
// */
// public void setNumberOfCores(Integer numberOfCores) {
// this.numberOfCores = numberOfCores;
// }
//
// /**
// * @return the memoryStatus
// */
// public MemoryStatus getMemoryStatus() {
// return memoryStatus;
// }
//
// /**
// * @param memoryStatus the memoryStatus to set
// */
// public void setMemoryStatus(MemoryStatus memoryStatus) {
// this.memoryStatus = memoryStatus;
// }
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/MiscResource.java
import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cytoscape.rest.internal.model.CytoscapeVersion;
import org.cytoscape.rest.internal.model.ServerStatus;
package org.cytoscape.rest.internal.resource;
/**
* Resource to provide general status of the Cytoscape REST server.
*
*
* @servicetag Server status
*
*/
@Singleton
@Path("/v1")
public class MiscResource extends AbstractResource {
/**
* @summary Cytoscape RESTful API server status
*
* @return Summary of server status
*
* @statuscode 500 If REST API Module is not working.
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8") | public ServerStatus getStatus() { |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/MiscResource.java | // Path: src/main/java/org/cytoscape/rest/internal/model/CytoscapeVersion.java
// @XmlRootElement
// public class CytoscapeVersion {
// private final String apiVersion;
// private final String cytoscapeVersion;
//
// public CytoscapeVersion(final String apiVersion, final String cytoscapeVersion) {
// this.apiVersion = apiVersion;
// this.cytoscapeVersion = cytoscapeVersion;
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @return the cytoscapeVersion
// */
// public String getCytoscapeVersion() {
// return cytoscapeVersion;
// }
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/model/ServerStatus.java
// @XmlRootElement
// public class ServerStatus {
//
// private String apiVersion;
// private Integer numberOfCores;
//
// private MemoryStatus memoryStatus;
//
//
// public ServerStatus() {
// this.setApiVersion("v1");
// this.setNumberOfCores(Runtime.getRuntime().availableProcessors());
// this.setMemoryStatus(new MemoryStatus());
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @param apiVersion
// * the apiVersion to set
// */
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// /**
// * @return the numberOfCores
// */
// public Integer getNumberOfCores() {
// return numberOfCores;
// }
//
// /**
// * @param numberOfCores
// * the numberOfCores to set
// */
// public void setNumberOfCores(Integer numberOfCores) {
// this.numberOfCores = numberOfCores;
// }
//
// /**
// * @return the memoryStatus
// */
// public MemoryStatus getMemoryStatus() {
// return memoryStatus;
// }
//
// /**
// * @param memoryStatus the memoryStatus to set
// */
// public void setMemoryStatus(MemoryStatus memoryStatus) {
// this.memoryStatus = memoryStatus;
// }
//
// }
| import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cytoscape.rest.internal.model.CytoscapeVersion;
import org.cytoscape.rest.internal.model.ServerStatus; | package org.cytoscape.rest.internal.resource;
/**
* Resource to provide general status of the Cytoscape REST server.
*
*
* @servicetag Server status
*
*/
@Singleton
@Path("/v1")
public class MiscResource extends AbstractResource {
/**
* @summary Cytoscape RESTful API server status
*
* @return Summary of server status
*
* @statuscode 500 If REST API Module is not working.
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ServerStatus getStatus() {
return new ServerStatus();
}
/**
* Run System.gc(). In general, this is not necessary.
*
* @summary Force to run garbage collection to free up memory
*/
@GET
@Path("/gc")
@Produces(MediaType.APPLICATION_JSON)
public void runGarbageCollection() {
Runtime.getRuntime().gc();
}
/**
*
* @summary Get Cytoscape and REST API version
*
* @return Cytoscape version and REST API version
*
*/
@GET
@Path("/version")
@Produces(MediaType.APPLICATION_JSON) | // Path: src/main/java/org/cytoscape/rest/internal/model/CytoscapeVersion.java
// @XmlRootElement
// public class CytoscapeVersion {
// private final String apiVersion;
// private final String cytoscapeVersion;
//
// public CytoscapeVersion(final String apiVersion, final String cytoscapeVersion) {
// this.apiVersion = apiVersion;
// this.cytoscapeVersion = cytoscapeVersion;
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @return the cytoscapeVersion
// */
// public String getCytoscapeVersion() {
// return cytoscapeVersion;
// }
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/model/ServerStatus.java
// @XmlRootElement
// public class ServerStatus {
//
// private String apiVersion;
// private Integer numberOfCores;
//
// private MemoryStatus memoryStatus;
//
//
// public ServerStatus() {
// this.setApiVersion("v1");
// this.setNumberOfCores(Runtime.getRuntime().availableProcessors());
// this.setMemoryStatus(new MemoryStatus());
// }
//
// /**
// * @return the apiVersion
// */
// public String getApiVersion() {
// return apiVersion;
// }
//
// /**
// * @param apiVersion
// * the apiVersion to set
// */
// public void setApiVersion(String apiVersion) {
// this.apiVersion = apiVersion;
// }
//
// /**
// * @return the numberOfCores
// */
// public Integer getNumberOfCores() {
// return numberOfCores;
// }
//
// /**
// * @param numberOfCores
// * the numberOfCores to set
// */
// public void setNumberOfCores(Integer numberOfCores) {
// this.numberOfCores = numberOfCores;
// }
//
// /**
// * @return the memoryStatus
// */
// public MemoryStatus getMemoryStatus() {
// return memoryStatus;
// }
//
// /**
// * @param memoryStatus the memoryStatus to set
// */
// public void setMemoryStatus(MemoryStatus memoryStatus) {
// this.memoryStatus = memoryStatus;
// }
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/MiscResource.java
import java.util.Properties;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cytoscape.rest.internal.model.CytoscapeVersion;
import org.cytoscape.rest.internal.model.ServerStatus;
package org.cytoscape.rest.internal.resource;
/**
* Resource to provide general status of the Cytoscape REST server.
*
*
* @servicetag Server status
*
*/
@Singleton
@Path("/v1")
public class MiscResource extends AbstractResource {
/**
* @summary Cytoscape RESTful API server status
*
* @return Summary of server status
*
* @statuscode 500 If REST API Module is not working.
*/
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public ServerStatus getStatus() {
return new ServerStatus();
}
/**
* Run System.gc(). In general, this is not necessary.
*
* @summary Force to run garbage collection to free up memory
*/
@GET
@Path("/gc")
@Produces(MediaType.APPLICATION_JSON)
public void runGarbageCollection() {
Runtime.getRuntime().gc();
}
/**
*
* @summary Get Cytoscape and REST API version
*
* @return Cytoscape version and REST API version
*
*/
@GET
@Path("/version")
@Produces(MediaType.APPLICATION_JSON) | public CytoscapeVersion getCytoscapeVersion() { |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/UIResource.java | // Path: src/main/java/org/cytoscape/rest/internal/CyActivator.java
// public class LevelOfDetails {
//
// private final NetworkTaskFactory lod;
//
// public LevelOfDetails(final NetworkTaskFactory tf) {
// this.lod = tf;
// }
//
// public NetworkTaskFactory getLodTF() {
// return lod;
// }
//
// }
| import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.swing.CytoPanel;
import org.cytoscape.application.swing.CytoPanelName;
import org.cytoscape.application.swing.CytoPanelState;
import org.cytoscape.rest.internal.CyActivator.LevelOfDetails;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.sym.Name;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/ui")
public class UIResource extends AbstractResource {
@Context
@NotNull
protected CySwingApplication desktop;
@Context
@NotNull | // Path: src/main/java/org/cytoscape/rest/internal/CyActivator.java
// public class LevelOfDetails {
//
// private final NetworkTaskFactory lod;
//
// public LevelOfDetails(final NetworkTaskFactory tf) {
// this.lod = tf;
// }
//
// public NetworkTaskFactory getLodTF() {
// return lod;
// }
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/UIResource.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.swing.CytoPanel;
import org.cytoscape.application.swing.CytoPanelName;
import org.cytoscape.application.swing.CytoPanelState;
import org.cytoscape.rest.internal.CyActivator.LevelOfDetails;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.sym.Name;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/ui")
public class UIResource extends AbstractResource {
@Context
@NotNull
protected CySwingApplication desktop;
@Context
@NotNull | protected LevelOfDetails detailsTF; |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/serializer/GraphObjectSerializer.java | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator; | JsonGenerator generator = null;
generator = factory.createGenerator(stream);
generator.writeStartArray();
for (final CyRow row : rows) {
generator.writeStartObject();
serializeSingleRow(generator, row);
generator.writeEndObject();
}
generator.writeEndArray();
generator.close();
result = stream.toString("UTF-8");
stream.close();
return result;
}
public final String serializeColumns(final Collection<CyColumn> columns) throws IOException {
final JsonFactory factory = new JsonFactory();
String result = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonGenerator generator = null;
generator = factory.createGenerator(stream);
generator.writeStartArray();
for (final CyColumn column : columns) {
generator.writeStartObject(); | // Path: src/main/java/org/cytoscape/rest/internal/resource/JsonTags.java
// public class JsonTags {
//
//
// // For JSON
//
// public static final String TITLE = "title";
// public static final String PUBLIC = "public";
// public static final String MUTABLE = "mutable";
// public static final String PRIMARY_KEY = "primaryKey";
// public static final String ROWS = "rows";
//
// public static final String COUNT = "count";
//
// public static final String COLUMN_NAME = "name";
// public static final String COLUMN_NAME_OLD = "oldName";
// public static final String COLUMN_NAME_NEW = "newName";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_VALUES = "values";
// public static final String COLUMN_IMMUTABLE = "immutable";
// public static final String COLUMN_IS_LIST = "list";
// public static final String COLUMN_IS_LOCAL = "local";
//
// public static final String TABLE_FORMAT = "format";
//
// public static final String SOURCE = "source";
// public static final String TARGET= "target";
// public static final String DIRECTED = "directed";
//
// public static final String NETWORK_SUID = "networkSUID";
//
// public static final String URL = "url";
// public static final String FORMAT_EDGELIST = "edgelist";
//
//
//
// }
// Path: src/main/java/org/cytoscape/rest/internal/serializer/GraphObjectSerializer.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyRow;
import org.cytoscape.rest.internal.resource.JsonTags;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
JsonGenerator generator = null;
generator = factory.createGenerator(stream);
generator.writeStartArray();
for (final CyRow row : rows) {
generator.writeStartObject();
serializeSingleRow(generator, row);
generator.writeEndObject();
}
generator.writeEndArray();
generator.close();
result = stream.toString("UTF-8");
stream.close();
return result;
}
public final String serializeColumns(final Collection<CyColumn> columns) throws IOException {
final JsonFactory factory = new JsonFactory();
String result = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JsonGenerator generator = null;
generator = factory.createGenerator(stream);
generator.writeStartArray();
for (final CyColumn column : columns) {
generator.writeStartObject(); | generator.writeStringField(JsonTags.COLUMN_NAME, column.getName()); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent; | package org.cytoscape.rest.internal.commands.resources;
/**
*
* JAX-RS Resource for all Command-related API
*
*
*/
@Singleton
@Path("/v1/commands")
public class CommandResource implements PaxAppender, TaskObserver {
@Context
@NotNull
private AvailableCommands available;
@Context
@NotNull
private CommandExecutorTaskFactory ceTaskFactory;
@Context
@NotNull
private SynchronousTaskManager<?> taskManager;
private CustomFailureException taskException; | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent;
package org.cytoscape.rest.internal.commands.resources;
/**
*
* JAX-RS Resource for all Command-related API
*
*
*/
@Singleton
@Path("/v1/commands")
public class CommandResource implements PaxAppender, TaskObserver {
@Context
@NotNull
private AvailableCommands available;
@Context
@NotNull
private CommandExecutorTaskFactory ceTaskFactory;
@Context
@NotNull
private SynchronousTaskManager<?> taskManager;
private CustomFailureException taskException; | private MessageHandler messageHandler; |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent; | package org.cytoscape.rest.internal.commands.resources;
/**
*
* JAX-RS Resource for all Command-related API
*
*
*/
@Singleton
@Path("/v1/commands")
public class CommandResource implements PaxAppender, TaskObserver {
@Context
@NotNull
private AvailableCommands available;
@Context
@NotNull
private CommandExecutorTaskFactory ceTaskFactory;
@Context
@NotNull
private SynchronousTaskManager<?> taskManager;
private CustomFailureException taskException;
private MessageHandler messageHandler;
private boolean processingCommand = false;
/**
* Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
public String enumerateNamespaces() { | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent;
package org.cytoscape.rest.internal.commands.resources;
/**
*
* JAX-RS Resource for all Command-related API
*
*
*/
@Singleton
@Path("/v1/commands")
public class CommandResource implements PaxAppender, TaskObserver {
@Context
@NotNull
private AvailableCommands available;
@Context
@NotNull
private CommandExecutorTaskFactory ceTaskFactory;
@Context
@NotNull
private SynchronousTaskManager<?> taskManager;
private CustomFailureException taskException;
private MessageHandler messageHandler;
private boolean processingCommand = false;
/**
* Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
public String enumerateNamespaces() { | final MessageHandler handler = new TextPlainHandler(); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent; | * Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
public String enumerateNamespaces() {
final MessageHandler handler = new TextPlainHandler();
final List<String> namespaces = available.getNamespaces();
handler.appendCommand("Available namespaces:");
for (final String namespace : namespaces) {
handler.appendMessage(" " + namespace);
}
return handler.getMessages();
}
/**
* Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/html" media type.
*
* @return String that will be returned as a text/html response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_HTML)
public String enumerateNamespacesHtml() { | // Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/MessageHandler.java
// public interface MessageHandler {
//
// public void appendCommand(final String s);
//
// public void appendError(final String s);
//
// public void appendWarning(final String s);
//
// public void appendResult(final Object s);
//
// public void appendMessage(final String s);
//
// public String getMessages();
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextHTMLHandler.java
// public class TextHTMLHandler implements MessageHandler {
// List<String> messages;
//
// public TextHTMLHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add("<p style=\"color:blue;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendError(String s) {
// messages.add("<p style=\"color:red;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendWarning(String s) {
// messages.add("<p style=\"color:yellow;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendResult(Object s) {
// messages.add("<p style=\"color:green;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public void appendMessage(String s) {
// messages.add("<p style=\"color:black;margin-left:10px;margin-top:0px;margin-bottom:5px;\">"
// + s + "</p>");
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/commands/handlers/TextPlainHandler.java
// public class TextPlainHandler implements MessageHandler {
// List<String> messages;
//
// public TextPlainHandler() {
// messages = new ArrayList<String>();
// }
//
// public void appendCommand(String s) {
// messages.add(s);
// }
//
// public void appendError(String s) {
// messages.add(s);
// }
//
// public void appendWarning(String s) {
// messages.add(s);
// }
//
// public void appendResult(Object s) {
// messages.add(s.toString());
// }
//
// public void appendMessage(String s) {
// messages.add(s);
// }
//
// public String getMessages() {
// String str = "";
// for (String s : messages) {
// str += s + "\n";
// }
// return str;
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/commands/resources/CommandResource.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.rest.internal.commands.handlers.MessageHandler;
import org.cytoscape.rest.internal.commands.handlers.TextHTMLHandler;
import org.cytoscape.rest.internal.commands.handlers.TextPlainHandler;
import org.cytoscape.work.FinishStatus;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskObserver;
import org.ops4j.pax.logging.spi.PaxAppender;
import org.ops4j.pax.logging.spi.PaxLevel;
import org.ops4j.pax.logging.spi.PaxLoggingEvent;
* Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/plain" media type.
*
* @return String that will be returned as a text/plain response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_PLAIN)
public String enumerateNamespaces() {
final MessageHandler handler = new TextPlainHandler();
final List<String> namespaces = available.getNamespaces();
handler.appendCommand("Available namespaces:");
for (final String namespace : namespaces) {
handler.appendMessage(" " + namespace);
}
return handler.getMessages();
}
/**
* Method handling HTTP GET requests to enumerate all namespaces. The
* returned list will be sent to the client as "text/html" media type.
*
* @return String that will be returned as a text/html response.
*/
@GET
@Path("/")
@Produces(MediaType.TEXT_HTML)
public String enumerateNamespacesHtml() { | final MessageHandler handler = new TextHTMLHandler(); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/AlgorithmicResource.java | // Path: src/main/java/org/cytoscape/rest/internal/EdgeBundler.java
// public interface EdgeBundler {
//
// NetworkTaskFactory getBundlerTF();
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/MapperUtil.java
// public class MapperUtil {
//
// public static final Class<?> getColumnClass(final String type) {
// if (type.equals(Double.class.getSimpleName())) {
// return Double.class;
// } else if (type.equals(Long.class.getSimpleName())) {
// return Long.class;
// } else if (type.equals(Integer.class.getSimpleName())) {
// return Integer.class;
// } else if (type.equals(Float.class.getSimpleName())) {
// return Float.class;
// } else if (type.equals(Boolean.class.getSimpleName())) {
// return Boolean.class;
// } else if (type.equals(String.class.getSimpleName())) {
// return String.class;
// } else if (type.equals(Number.class.getSimpleName())) {
// return Double.class;
// } else {
// return null;
// }
// }
//
// public static final Object getRawValue(final String queryString, Class<?> type) {
// Object raw = queryString;
//
// if (type == Boolean.class) {
// raw = Boolean.parseBoolean(queryString);
// } else if (type == Double.class) {
// raw = Double.parseDouble(queryString);
// } else if (type == Integer.class) {
// raw = Integer.parseInt(queryString);
// } else if (type == Long.class) {
// raw = Long.parseLong(queryString);
// } else if (type == Float.class) {
// raw = Float.parseFloat(queryString);
// }
// return raw;
// }
//
// public static final Object getValue(final JsonNode value, final Class<?> type) {
// if (type == String.class) {
// return value.asText();
// } else if (type == Boolean.class || type.getSimpleName() == "boolean") {
// return value.asBoolean();
// } else if (type == Double.class || type.getSimpleName() == "double") {
// return value.asDouble();
// } else if (type == Integer.class || type.getSimpleName() == "int") {
// return value.asInt();
// } else if (type == Long.class || type.getSimpleName() == "long") {
// return value.asLong();
// } else if (type == Float.class || type.getSimpleName() == "float") {
// return value.asDouble();
// } else {
// return null;
// }
// }
// }
| import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.rest.internal.EdgeBundler;
import org.cytoscape.rest.internal.datamapper.MapperUtil;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.internal.resource;
/**
*
* Algorithmic resources.
* Runs Cytoscape tasks, such as layouts or apply Style.
*
*/
@Singleton
@Path("/v1/apply")
public class AlgorithmicResource extends AbstractResource {
@Context
@NotNull
private TaskMonitor headlessTaskMonitor;
@Context
@NotNull
private CyLayoutAlgorithmManager layoutManager;
@Context
@NotNull
private NetworkTaskFactory fitContent;
@Context
@NotNull | // Path: src/main/java/org/cytoscape/rest/internal/EdgeBundler.java
// public interface EdgeBundler {
//
// NetworkTaskFactory getBundlerTF();
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/MapperUtil.java
// public class MapperUtil {
//
// public static final Class<?> getColumnClass(final String type) {
// if (type.equals(Double.class.getSimpleName())) {
// return Double.class;
// } else if (type.equals(Long.class.getSimpleName())) {
// return Long.class;
// } else if (type.equals(Integer.class.getSimpleName())) {
// return Integer.class;
// } else if (type.equals(Float.class.getSimpleName())) {
// return Float.class;
// } else if (type.equals(Boolean.class.getSimpleName())) {
// return Boolean.class;
// } else if (type.equals(String.class.getSimpleName())) {
// return String.class;
// } else if (type.equals(Number.class.getSimpleName())) {
// return Double.class;
// } else {
// return null;
// }
// }
//
// public static final Object getRawValue(final String queryString, Class<?> type) {
// Object raw = queryString;
//
// if (type == Boolean.class) {
// raw = Boolean.parseBoolean(queryString);
// } else if (type == Double.class) {
// raw = Double.parseDouble(queryString);
// } else if (type == Integer.class) {
// raw = Integer.parseInt(queryString);
// } else if (type == Long.class) {
// raw = Long.parseLong(queryString);
// } else if (type == Float.class) {
// raw = Float.parseFloat(queryString);
// }
// return raw;
// }
//
// public static final Object getValue(final JsonNode value, final Class<?> type) {
// if (type == String.class) {
// return value.asText();
// } else if (type == Boolean.class || type.getSimpleName() == "boolean") {
// return value.asBoolean();
// } else if (type == Double.class || type.getSimpleName() == "double") {
// return value.asDouble();
// } else if (type == Integer.class || type.getSimpleName() == "int") {
// return value.asInt();
// } else if (type == Long.class || type.getSimpleName() == "long") {
// return value.asLong();
// } else if (type == Float.class || type.getSimpleName() == "float") {
// return value.asDouble();
// } else {
// return null;
// }
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/AlgorithmicResource.java
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.rest.internal.EdgeBundler;
import org.cytoscape.rest.internal.datamapper.MapperUtil;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.internal.resource;
/**
*
* Algorithmic resources.
* Runs Cytoscape tasks, such as layouts or apply Style.
*
*/
@Singleton
@Path("/v1/apply")
public class AlgorithmicResource extends AbstractResource {
@Context
@NotNull
private TaskMonitor headlessTaskMonitor;
@Context
@NotNull
private CyLayoutAlgorithmManager layoutManager;
@Context
@NotNull
private NetworkTaskFactory fitContent;
@Context
@NotNull | private EdgeBundler edgeBundler; |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/AlgorithmicResource.java | // Path: src/main/java/org/cytoscape/rest/internal/EdgeBundler.java
// public interface EdgeBundler {
//
// NetworkTaskFactory getBundlerTF();
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/MapperUtil.java
// public class MapperUtil {
//
// public static final Class<?> getColumnClass(final String type) {
// if (type.equals(Double.class.getSimpleName())) {
// return Double.class;
// } else if (type.equals(Long.class.getSimpleName())) {
// return Long.class;
// } else if (type.equals(Integer.class.getSimpleName())) {
// return Integer.class;
// } else if (type.equals(Float.class.getSimpleName())) {
// return Float.class;
// } else if (type.equals(Boolean.class.getSimpleName())) {
// return Boolean.class;
// } else if (type.equals(String.class.getSimpleName())) {
// return String.class;
// } else if (type.equals(Number.class.getSimpleName())) {
// return Double.class;
// } else {
// return null;
// }
// }
//
// public static final Object getRawValue(final String queryString, Class<?> type) {
// Object raw = queryString;
//
// if (type == Boolean.class) {
// raw = Boolean.parseBoolean(queryString);
// } else if (type == Double.class) {
// raw = Double.parseDouble(queryString);
// } else if (type == Integer.class) {
// raw = Integer.parseInt(queryString);
// } else if (type == Long.class) {
// raw = Long.parseLong(queryString);
// } else if (type == Float.class) {
// raw = Float.parseFloat(queryString);
// }
// return raw;
// }
//
// public static final Object getValue(final JsonNode value, final Class<?> type) {
// if (type == String.class) {
// return value.asText();
// } else if (type == Boolean.class || type.getSimpleName() == "boolean") {
// return value.asBoolean();
// } else if (type == Double.class || type.getSimpleName() == "double") {
// return value.asDouble();
// } else if (type == Integer.class || type.getSimpleName() == "int") {
// return value.asInt();
// } else if (type == Long.class || type.getSimpleName() == "long") {
// return value.asLong();
// } else if (type == Float.class || type.getSimpleName() == "float") {
// return value.asDouble();
// } else {
// return null;
// }
// }
// }
| import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.rest.internal.EdgeBundler;
import org.cytoscape.rest.internal.datamapper.MapperUtil;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | * <li>value: New value for the parameter field</li>
* </ul>
*
* @summary Update layout parameters for the algorithm
*
* @param algorithmName Name of the layout algorithm
*
* @return Response code 200 if success
*/
@PUT
@Path("/layouts/{algorithmName}/parameters")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateLayoutParameters(@PathParam("algorithmName") String algorithmName, final InputStream is) {
final ObjectMapper objMapper = new ObjectMapper();
final CyLayoutAlgorithm layout = this.layoutManager.getLayout(algorithmName);
final Object context = layout.getDefaultLayoutContext();
try {
final Map<String, Class<?>> params = getParameterTypes(layout);
// This should be an JSON array.
final JsonNode rootNode = objMapper.readValue(is, JsonNode.class);
for (final JsonNode entry : rootNode) {
final String parameterName = entry.get("name").asText();
final Class<?> type = params.get(parameterName);
if(type == null) {
throw new NotFoundException("No such parameter: " + parameterName);
}
final JsonNode val = entry.get("value"); | // Path: src/main/java/org/cytoscape/rest/internal/EdgeBundler.java
// public interface EdgeBundler {
//
// NetworkTaskFactory getBundlerTF();
//
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/MapperUtil.java
// public class MapperUtil {
//
// public static final Class<?> getColumnClass(final String type) {
// if (type.equals(Double.class.getSimpleName())) {
// return Double.class;
// } else if (type.equals(Long.class.getSimpleName())) {
// return Long.class;
// } else if (type.equals(Integer.class.getSimpleName())) {
// return Integer.class;
// } else if (type.equals(Float.class.getSimpleName())) {
// return Float.class;
// } else if (type.equals(Boolean.class.getSimpleName())) {
// return Boolean.class;
// } else if (type.equals(String.class.getSimpleName())) {
// return String.class;
// } else if (type.equals(Number.class.getSimpleName())) {
// return Double.class;
// } else {
// return null;
// }
// }
//
// public static final Object getRawValue(final String queryString, Class<?> type) {
// Object raw = queryString;
//
// if (type == Boolean.class) {
// raw = Boolean.parseBoolean(queryString);
// } else if (type == Double.class) {
// raw = Double.parseDouble(queryString);
// } else if (type == Integer.class) {
// raw = Integer.parseInt(queryString);
// } else if (type == Long.class) {
// raw = Long.parseLong(queryString);
// } else if (type == Float.class) {
// raw = Float.parseFloat(queryString);
// }
// return raw;
// }
//
// public static final Object getValue(final JsonNode value, final Class<?> type) {
// if (type == String.class) {
// return value.asText();
// } else if (type == Boolean.class || type.getSimpleName() == "boolean") {
// return value.asBoolean();
// } else if (type == Double.class || type.getSimpleName() == "double") {
// return value.asDouble();
// } else if (type == Integer.class || type.getSimpleName() == "int") {
// return value.asInt();
// } else if (type == Long.class || type.getSimpleName() == "long") {
// return value.asLong();
// } else if (type == Float.class || type.getSimpleName() == "float") {
// return value.asDouble();
// } else {
// return null;
// }
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/AlgorithmicResource.java
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.rest.internal.EdgeBundler;
import org.cytoscape.rest.internal.datamapper.MapperUtil;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithm;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
* <li>value: New value for the parameter field</li>
* </ul>
*
* @summary Update layout parameters for the algorithm
*
* @param algorithmName Name of the layout algorithm
*
* @return Response code 200 if success
*/
@PUT
@Path("/layouts/{algorithmName}/parameters")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateLayoutParameters(@PathParam("algorithmName") String algorithmName, final InputStream is) {
final ObjectMapper objMapper = new ObjectMapper();
final CyLayoutAlgorithm layout = this.layoutManager.getLayout(algorithmName);
final Object context = layout.getDefaultLayoutContext();
try {
final Map<String, Class<?>> params = getParameterTypes(layout);
// This should be an JSON array.
final JsonNode rootNode = objMapper.readValue(is, JsonNode.class);
for (final JsonNode entry : rootNode) {
final String parameterName = entry.get("name").asText();
final Class<?> type = params.get(parameterName);
if(type == null) {
throw new NotFoundException("No such parameter: " + parameterName);
}
final JsonNode val = entry.get("value"); | final Object value = MapperUtil.getValue(val, params.get(parameterName)); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/GroupResource.java | // Path: src/main/java/org/cytoscape/rest/internal/datamapper/GroupMapper.java
// public class GroupMapper {
//
//
// /**
// * Create a new group from a list of nodes.
// *
// * @param rootNode
// * @param factory
// * @param network
// * @return
// */
// public CyGroup createGroup(final JsonNode rootNode, final CyGroupFactory factory, final CyNetwork network) {
//
// // Extract required fields: member nodes and name of new node.
// final String groupName = rootNode.get(CyNetwork.NAME).textValue();
// final JsonNode memberNodes = rootNode.get("nodes");
//
// // This is optional.
// final JsonNode memberEdges = rootNode.get("edges");
//
// if(groupName == null || groupName.isEmpty()) {
// throw new IllegalArgumentException("Group name is missing.");
// }
//
// if(memberNodes.isArray() == false) {
// throw new IllegalArgumentException("Invalid parameter.");
// }
//
// if(memberNodes.size() == 0) {
// throw new IllegalArgumentException("Group member list is empty.");
// }
//
// // Phase 1: Create list of member nodes.
// final List<CyNode> nodes = new ArrayList<CyNode>();
// for (final JsonNode node : memberNodes) {
// final CyNode n = network.getNode(node.asLong());
// if (n != null) {
// nodes.add(n);
// }
// }
//
// // Phase 2: Create group from the list of nodes.
// final CyGroup group = factory.createGroup(network, nodes, null, true);
// final CyRow groupRow = ((CySubNetwork)network).getRootNetwork().getRow(group.getGroupNode(), CyRootNetwork.SHARED_ATTRS);
// groupRow.set(CyRootNetwork.SHARED_NAME, groupName);
//
// // Add edges if necessary...
// if (memberEdges != null && memberEdges.isArray()) {
// final List<CyEdge> edges = new ArrayList<CyEdge>();
// for (final JsonNode edge : memberEdges) {
// final CyEdge e = network.getEdge(edge.asLong());
// if (e != null) {
// edges.add(e);
// }
// }
// group.addEdges(edges);
// }
//
// return group;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/serializer/GroupModule.java
// public class GroupModule extends SimpleModule {
//
// private static final long serialVersionUID = -1590853632349015561L;
//
// public GroupModule() {
// super("GroupModule", new Version(1, 0, 0, null, null, null));
// addSerializer(new GroupSerializer());
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.rest.internal.datamapper.GroupMapper;
import org.cytoscape.rest.internal.serializer.GroupModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/networks/{networkId}/groups")
public class GroupResource extends AbstractResource {
private final ObjectMapper groupMapper; | // Path: src/main/java/org/cytoscape/rest/internal/datamapper/GroupMapper.java
// public class GroupMapper {
//
//
// /**
// * Create a new group from a list of nodes.
// *
// * @param rootNode
// * @param factory
// * @param network
// * @return
// */
// public CyGroup createGroup(final JsonNode rootNode, final CyGroupFactory factory, final CyNetwork network) {
//
// // Extract required fields: member nodes and name of new node.
// final String groupName = rootNode.get(CyNetwork.NAME).textValue();
// final JsonNode memberNodes = rootNode.get("nodes");
//
// // This is optional.
// final JsonNode memberEdges = rootNode.get("edges");
//
// if(groupName == null || groupName.isEmpty()) {
// throw new IllegalArgumentException("Group name is missing.");
// }
//
// if(memberNodes.isArray() == false) {
// throw new IllegalArgumentException("Invalid parameter.");
// }
//
// if(memberNodes.size() == 0) {
// throw new IllegalArgumentException("Group member list is empty.");
// }
//
// // Phase 1: Create list of member nodes.
// final List<CyNode> nodes = new ArrayList<CyNode>();
// for (final JsonNode node : memberNodes) {
// final CyNode n = network.getNode(node.asLong());
// if (n != null) {
// nodes.add(n);
// }
// }
//
// // Phase 2: Create group from the list of nodes.
// final CyGroup group = factory.createGroup(network, nodes, null, true);
// final CyRow groupRow = ((CySubNetwork)network).getRootNetwork().getRow(group.getGroupNode(), CyRootNetwork.SHARED_ATTRS);
// groupRow.set(CyRootNetwork.SHARED_NAME, groupName);
//
// // Add edges if necessary...
// if (memberEdges != null && memberEdges.isArray()) {
// final List<CyEdge> edges = new ArrayList<CyEdge>();
// for (final JsonNode edge : memberEdges) {
// final CyEdge e = network.getEdge(edge.asLong());
// if (e != null) {
// edges.add(e);
// }
// }
// group.addEdges(edges);
// }
//
// return group;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/serializer/GroupModule.java
// public class GroupModule extends SimpleModule {
//
// private static final long serialVersionUID = -1590853632349015561L;
//
// public GroupModule() {
// super("GroupModule", new Version(1, 0, 0, null, null, null));
// addSerializer(new GroupSerializer());
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/GroupResource.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.rest.internal.datamapper.GroupMapper;
import org.cytoscape.rest.internal.serializer.GroupModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/networks/{networkId}/groups")
public class GroupResource extends AbstractResource {
private final ObjectMapper groupMapper; | private final GroupMapper mapper; |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/resource/GroupResource.java | // Path: src/main/java/org/cytoscape/rest/internal/datamapper/GroupMapper.java
// public class GroupMapper {
//
//
// /**
// * Create a new group from a list of nodes.
// *
// * @param rootNode
// * @param factory
// * @param network
// * @return
// */
// public CyGroup createGroup(final JsonNode rootNode, final CyGroupFactory factory, final CyNetwork network) {
//
// // Extract required fields: member nodes and name of new node.
// final String groupName = rootNode.get(CyNetwork.NAME).textValue();
// final JsonNode memberNodes = rootNode.get("nodes");
//
// // This is optional.
// final JsonNode memberEdges = rootNode.get("edges");
//
// if(groupName == null || groupName.isEmpty()) {
// throw new IllegalArgumentException("Group name is missing.");
// }
//
// if(memberNodes.isArray() == false) {
// throw new IllegalArgumentException("Invalid parameter.");
// }
//
// if(memberNodes.size() == 0) {
// throw new IllegalArgumentException("Group member list is empty.");
// }
//
// // Phase 1: Create list of member nodes.
// final List<CyNode> nodes = new ArrayList<CyNode>();
// for (final JsonNode node : memberNodes) {
// final CyNode n = network.getNode(node.asLong());
// if (n != null) {
// nodes.add(n);
// }
// }
//
// // Phase 2: Create group from the list of nodes.
// final CyGroup group = factory.createGroup(network, nodes, null, true);
// final CyRow groupRow = ((CySubNetwork)network).getRootNetwork().getRow(group.getGroupNode(), CyRootNetwork.SHARED_ATTRS);
// groupRow.set(CyRootNetwork.SHARED_NAME, groupName);
//
// // Add edges if necessary...
// if (memberEdges != null && memberEdges.isArray()) {
// final List<CyEdge> edges = new ArrayList<CyEdge>();
// for (final JsonNode edge : memberEdges) {
// final CyEdge e = network.getEdge(edge.asLong());
// if (e != null) {
// edges.add(e);
// }
// }
// group.addEdges(edges);
// }
//
// return group;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/serializer/GroupModule.java
// public class GroupModule extends SimpleModule {
//
// private static final long serialVersionUID = -1590853632349015561L;
//
// public GroupModule() {
// super("GroupModule", new Version(1, 0, 0, null, null, null));
// addSerializer(new GroupSerializer());
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.rest.internal.datamapper.GroupMapper;
import org.cytoscape.rest.internal.serializer.GroupModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; | package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/networks/{networkId}/groups")
public class GroupResource extends AbstractResource {
private final ObjectMapper groupMapper;
private final GroupMapper mapper;
@Context
private CyGroupFactory groupFactory;
@Context
private CyGroupManager groupManager;
public GroupResource() {
super();
this.groupMapper = new ObjectMapper(); | // Path: src/main/java/org/cytoscape/rest/internal/datamapper/GroupMapper.java
// public class GroupMapper {
//
//
// /**
// * Create a new group from a list of nodes.
// *
// * @param rootNode
// * @param factory
// * @param network
// * @return
// */
// public CyGroup createGroup(final JsonNode rootNode, final CyGroupFactory factory, final CyNetwork network) {
//
// // Extract required fields: member nodes and name of new node.
// final String groupName = rootNode.get(CyNetwork.NAME).textValue();
// final JsonNode memberNodes = rootNode.get("nodes");
//
// // This is optional.
// final JsonNode memberEdges = rootNode.get("edges");
//
// if(groupName == null || groupName.isEmpty()) {
// throw new IllegalArgumentException("Group name is missing.");
// }
//
// if(memberNodes.isArray() == false) {
// throw new IllegalArgumentException("Invalid parameter.");
// }
//
// if(memberNodes.size() == 0) {
// throw new IllegalArgumentException("Group member list is empty.");
// }
//
// // Phase 1: Create list of member nodes.
// final List<CyNode> nodes = new ArrayList<CyNode>();
// for (final JsonNode node : memberNodes) {
// final CyNode n = network.getNode(node.asLong());
// if (n != null) {
// nodes.add(n);
// }
// }
//
// // Phase 2: Create group from the list of nodes.
// final CyGroup group = factory.createGroup(network, nodes, null, true);
// final CyRow groupRow = ((CySubNetwork)network).getRootNetwork().getRow(group.getGroupNode(), CyRootNetwork.SHARED_ATTRS);
// groupRow.set(CyRootNetwork.SHARED_NAME, groupName);
//
// // Add edges if necessary...
// if (memberEdges != null && memberEdges.isArray()) {
// final List<CyEdge> edges = new ArrayList<CyEdge>();
// for (final JsonNode edge : memberEdges) {
// final CyEdge e = network.getEdge(edge.asLong());
// if (e != null) {
// edges.add(e);
// }
// }
// group.addEdges(edges);
// }
//
// return group;
// }
// }
//
// Path: src/main/java/org/cytoscape/rest/internal/serializer/GroupModule.java
// public class GroupModule extends SimpleModule {
//
// private static final long serialVersionUID = -1590853632349015561L;
//
// public GroupModule() {
// super("GroupModule", new Version(1, 0, 0, null, null, null));
// addSerializer(new GroupSerializer());
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/resource/GroupResource.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.rest.internal.datamapper.GroupMapper;
import org.cytoscape.rest.internal.serializer.GroupModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.cytoscape.rest.internal.resource;
@Singleton
@Path("/v1/networks/{networkId}/groups")
public class GroupResource extends AbstractResource {
private final ObjectMapper groupMapper;
private final GroupMapper mapper;
@Context
private CyGroupFactory groupFactory;
@Context
private CyGroupManager groupManager;
public GroupResource() {
super();
this.groupMapper = new ObjectMapper(); | this.groupMapper.registerModule(new GroupModule()); |
idekerlab/cyREST | src/main/java/org/cytoscape/rest/internal/datamapper/VisualStyleMapper.java | // Path: src/main/java/org/cytoscape/rest/internal/MappingFactoryManager.java
// @MireDotIgnore
// public class MappingFactoryManager {
//
// private final Map<Class<?>, VisualMappingFunctionFactory> factories;
//
// public MappingFactoryManager() {
// factories = new HashMap<Class<?>, VisualMappingFunctionFactory>();
// }
//
// public VisualMappingFunctionFactory getFactory(Class<?> mappingType) {
// return factories.get(mappingType);
// }
//
// @SuppressWarnings("rawtypes")
// public void addFactory(VisualMappingFunctionFactory factory, Map properties) {
// factories.put(factory.getMappingFunctionType(), factory);
// }
//
// @SuppressWarnings("rawtypes")
// public void removeFactory(VisualMappingFunctionFactory factory, Map properties) {
// factories.remove(factory.getMappingFunctionType());
// }
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.rest.internal.MappingFactoryManager;
import org.cytoscape.view.model.View;
import org.cytoscape.view.model.VisualLexicon;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.vizmap.VisualMappingFunction;
import org.cytoscape.view.vizmap.VisualMappingFunctionFactory;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues;
import org.cytoscape.view.vizmap.mappings.ContinuousMapping;
import org.cytoscape.view.vizmap.mappings.DiscreteMapping;
import org.cytoscape.view.vizmap.mappings.PassthroughMapping;
import com.fasterxml.jackson.databind.JsonNode;
import com.qmino.miredot.annotations.MireDotIgnore; | package org.cytoscape.rest.internal.datamapper;
@MireDotIgnore
public class VisualStyleMapper {
private static final String TITLE = "title";
private static final String MAPPINGS = "mappings";
private static final String DEFAULTS = "defaults";
public static final String MAPPING_TYPE = "mappingType";
private static final String MAPPING_DISCRETE = "discrete";
private static final String MAPPING_PASSTHROUGH = "passthrough";
private static final String MAPPING_CONTINUOUS = "continuous";
public static final String MAPPING_COLUMN = "mappingColumn";
public static final String MAPPING_COLUMN_TYPE = "mappingColumnType";
public static final String MAPPING_VP = "visualProperty";
private static final String MAPPING_DISCRETE_MAP = "map";
private static final String MAPPING_DISCRETE_KEY = "key";
private static final String MAPPING_DISCRETE_VALUE = "value";
public static final String VP_DEPENDENCY = "visualPropertyDependency";
public static final String VP_DEPENDENCY_ENABLED = "enabled";
| // Path: src/main/java/org/cytoscape/rest/internal/MappingFactoryManager.java
// @MireDotIgnore
// public class MappingFactoryManager {
//
// private final Map<Class<?>, VisualMappingFunctionFactory> factories;
//
// public MappingFactoryManager() {
// factories = new HashMap<Class<?>, VisualMappingFunctionFactory>();
// }
//
// public VisualMappingFunctionFactory getFactory(Class<?> mappingType) {
// return factories.get(mappingType);
// }
//
// @SuppressWarnings("rawtypes")
// public void addFactory(VisualMappingFunctionFactory factory, Map properties) {
// factories.put(factory.getMappingFunctionType(), factory);
// }
//
// @SuppressWarnings("rawtypes")
// public void removeFactory(VisualMappingFunctionFactory factory, Map properties) {
// factories.remove(factory.getMappingFunctionType());
// }
// }
// Path: src/main/java/org/cytoscape/rest/internal/datamapper/VisualStyleMapper.java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.Response;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.rest.internal.MappingFactoryManager;
import org.cytoscape.view.model.View;
import org.cytoscape.view.model.VisualLexicon;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.vizmap.VisualMappingFunction;
import org.cytoscape.view.vizmap.VisualMappingFunctionFactory;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues;
import org.cytoscape.view.vizmap.mappings.ContinuousMapping;
import org.cytoscape.view.vizmap.mappings.DiscreteMapping;
import org.cytoscape.view.vizmap.mappings.PassthroughMapping;
import com.fasterxml.jackson.databind.JsonNode;
import com.qmino.miredot.annotations.MireDotIgnore;
package org.cytoscape.rest.internal.datamapper;
@MireDotIgnore
public class VisualStyleMapper {
private static final String TITLE = "title";
private static final String MAPPINGS = "mappings";
private static final String DEFAULTS = "defaults";
public static final String MAPPING_TYPE = "mappingType";
private static final String MAPPING_DISCRETE = "discrete";
private static final String MAPPING_PASSTHROUGH = "passthrough";
private static final String MAPPING_CONTINUOUS = "continuous";
public static final String MAPPING_COLUMN = "mappingColumn";
public static final String MAPPING_COLUMN_TYPE = "mappingColumnType";
public static final String MAPPING_VP = "visualProperty";
private static final String MAPPING_DISCRETE_MAP = "map";
private static final String MAPPING_DISCRETE_KEY = "key";
private static final String MAPPING_DISCRETE_VALUE = "value";
public static final String VP_DEPENDENCY = "visualPropertyDependency";
public static final String VP_DEPENDENCY_ENABLED = "enabled";
| public VisualStyle buildVisualStyle(final MappingFactoryManager factoryManager, final VisualStyleFactory factory, |
kwatters/solrgraph | src/test/java/com/kmwllc/search/solr/client/TermTest.java | // Path: src/main/java/com/kmwllc/search/solr/client/Term.java
// public class Term {
//
// protected static final String SEP = ":";
// protected static final String EOLN = "";
//
// private String field;
// private String term;
// private float boost;
//
// public Term(String field, String term) {
// super();
// this.field = field;
// this.term = term;
// this.boost = -1;
// }
//
// public Term(String field, String term, float boost) {
// super();
// this.field = field;
// this.term = term;
// this.boost = boost;
// }
//
// public String getField() {
// return field;
// }
//
// public void setField(String field) {
// this.field = field;
// }
//
// public String getTerm() {
// return term;
// }
//
// public void setTerm(String term) {
// this.term = term;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((field == null) ? 0 : field.hashCode());
// result = prime * result + ((term == null) ? 0 : term.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Term other = (Term) obj;
// if (field == null) {
// if (other.field != null)
// return false;
// } else if (!field.equals(other.field))
// return false;
// if (term == null) {
// if (other.term != null)
// return false;
// } else if (!term.equals(other.term))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// // return "TERM(" + field + SEP + term + ")\n";
// // TODO: add the boost value if non default.
//
// // we need to escape the term for the sep
// String escaped = term.replaceAll(SEP, "\\" + SEP);
//
// if ((escaped.contains(" ") || escaped.contains(",")) && !escaped.startsWith("\"") && !escaped.endsWith("\"")) {
// escaped = escaped.replace("\"", "\\\"");
// escaped = "\"" + escaped + "\"";
// }
//
// return "" + field + SEP + escaped + EOLN;
// }
//
// public float getBoost() {
// return boost;
// }
//
// public void setBoost(float boost) {
// this.boost = boost;
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import com.kmwllc.search.solr.client.Term;
| package com.kmwllc.search.solr.client;
public class TermTest extends Assert {
@Test
public void testTerm() {
| // Path: src/main/java/com/kmwllc/search/solr/client/Term.java
// public class Term {
//
// protected static final String SEP = ":";
// protected static final String EOLN = "";
//
// private String field;
// private String term;
// private float boost;
//
// public Term(String field, String term) {
// super();
// this.field = field;
// this.term = term;
// this.boost = -1;
// }
//
// public Term(String field, String term, float boost) {
// super();
// this.field = field;
// this.term = term;
// this.boost = boost;
// }
//
// public String getField() {
// return field;
// }
//
// public void setField(String field) {
// this.field = field;
// }
//
// public String getTerm() {
// return term;
// }
//
// public void setTerm(String term) {
// this.term = term;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((field == null) ? 0 : field.hashCode());
// result = prime * result + ((term == null) ? 0 : term.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Term other = (Term) obj;
// if (field == null) {
// if (other.field != null)
// return false;
// } else if (!field.equals(other.field))
// return false;
// if (term == null) {
// if (other.term != null)
// return false;
// } else if (!term.equals(other.term))
// return false;
// return true;
// }
//
// @Override
// public String toString() {
// // return "TERM(" + field + SEP + term + ")\n";
// // TODO: add the boost value if non default.
//
// // we need to escape the term for the sep
// String escaped = term.replaceAll(SEP, "\\" + SEP);
//
// if ((escaped.contains(" ") || escaped.contains(",")) && !escaped.startsWith("\"") && !escaped.endsWith("\"")) {
// escaped = escaped.replace("\"", "\\\"");
// escaped = "\"" + escaped + "\"";
// }
//
// return "" + field + SEP + escaped + EOLN;
// }
//
// public float getBoost() {
// return boost;
// }
//
// public void setBoost(float boost) {
// this.boost = boost;
// }
//
// }
// Path: src/test/java/com/kmwllc/search/solr/client/TermTest.java
import org.junit.Assert;
import org.junit.Test;
import com.kmwllc.search.solr.client.Term;
package com.kmwllc.search.solr.client;
public class TermTest extends Assert {
@Test
public void testTerm() {
| Term t1 = new Term("text", "term");
|
Hatzen/PrismatikRemote | app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/commands/ToggleStatus.java | // Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/RemoteState.java
// public class RemoteState {
//
// public enum Status {
// ON,
// OFF,
// DEVICE_ERROR,
// UNKNOWN
// }
//
// public enum Mode {
// AMBILIGHT,
// MOODLAMP
// }
//
// private Status status = Status.UNKNOWN;
// private Mode mode = Mode.AMBILIGHT;
// private boolean statusApi;
// private ArrayList<String> profiles;
// private String profile;
// private int countLeds;
// private ArrayList<Rect> leds;
// private ArrayList<Integer> colors;
// private double gamma;
// private int brightness;
// private int smoothness;
//
// private static final RemoteState INSTANCE = new RemoteState();
//
// private RemoteState() {}
//
// public ArrayList<Integer> getColors() {
// return colors;
// }
//
// public void setColors(ArrayList<Integer> colors) {
// this.colors = colors;
// }
//
// public ArrayList<Rect> getLeds() {
// return leds;
// }
//
// public void setLeds(ArrayList<Rect> leds) {
// this.leds = leds;
// }
//
// public static RemoteState getInstance() {
// return INSTANCE;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public boolean isStatusApi() {
// return statusApi;
// }
//
// public void setStatusApi(boolean statusApi) {
// this.statusApi = statusApi;
// }
//
// public ArrayList<String> getProfiles() {
// return profiles;
// }
//
// public void setProfiles(ArrayList<String> profiles) {
// this.profiles = profiles;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public int getCountLeds() {
// return countLeds;
// }
//
// public void setCountLeds(int countLeds) {
// this.countLeds = countLeds;
// }
//
// public Mode getMode() {
// return mode;
// }
//
// public void setMode(Mode mode) {
// this.mode = mode;
// }
//
// public double getGamma() {
// return gamma;
// }
//
// public void setGamma(double gamma) {
// this.gamma = gamma;
// }
//
// public int getBrightness() {
// return brightness;
// }
//
// public void setBrightness(int brightness) {
// this.brightness = brightness;
// }
//
// public int getSmoothness() {
// return smoothness;
// }
//
// public void setSmoothness(int smoothness) {
// this.smoothness = smoothness;
// }
//
// }
| import de.prismatikremote.hartz.prismatikremote.backend.RemoteState; | package de.prismatikremote.hartz.prismatikremote.backend.commands;
/**
* Created by kaiha on 09.04.2017.
*/
public class ToggleStatus extends Communication {
private static String TAG = "ToggleStatus";
@Override
public String getCommand() {
String command = "setstatus:on"; | // Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/RemoteState.java
// public class RemoteState {
//
// public enum Status {
// ON,
// OFF,
// DEVICE_ERROR,
// UNKNOWN
// }
//
// public enum Mode {
// AMBILIGHT,
// MOODLAMP
// }
//
// private Status status = Status.UNKNOWN;
// private Mode mode = Mode.AMBILIGHT;
// private boolean statusApi;
// private ArrayList<String> profiles;
// private String profile;
// private int countLeds;
// private ArrayList<Rect> leds;
// private ArrayList<Integer> colors;
// private double gamma;
// private int brightness;
// private int smoothness;
//
// private static final RemoteState INSTANCE = new RemoteState();
//
// private RemoteState() {}
//
// public ArrayList<Integer> getColors() {
// return colors;
// }
//
// public void setColors(ArrayList<Integer> colors) {
// this.colors = colors;
// }
//
// public ArrayList<Rect> getLeds() {
// return leds;
// }
//
// public void setLeds(ArrayList<Rect> leds) {
// this.leds = leds;
// }
//
// public static RemoteState getInstance() {
// return INSTANCE;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public boolean isStatusApi() {
// return statusApi;
// }
//
// public void setStatusApi(boolean statusApi) {
// this.statusApi = statusApi;
// }
//
// public ArrayList<String> getProfiles() {
// return profiles;
// }
//
// public void setProfiles(ArrayList<String> profiles) {
// this.profiles = profiles;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public int getCountLeds() {
// return countLeds;
// }
//
// public void setCountLeds(int countLeds) {
// this.countLeds = countLeds;
// }
//
// public Mode getMode() {
// return mode;
// }
//
// public void setMode(Mode mode) {
// this.mode = mode;
// }
//
// public double getGamma() {
// return gamma;
// }
//
// public void setGamma(double gamma) {
// this.gamma = gamma;
// }
//
// public int getBrightness() {
// return brightness;
// }
//
// public void setBrightness(int brightness) {
// this.brightness = brightness;
// }
//
// public int getSmoothness() {
// return smoothness;
// }
//
// public void setSmoothness(int smoothness) {
// this.smoothness = smoothness;
// }
//
// }
// Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/commands/ToggleStatus.java
import de.prismatikremote.hartz.prismatikremote.backend.RemoteState;
package de.prismatikremote.hartz.prismatikremote.backend.commands;
/**
* Created by kaiha on 09.04.2017.
*/
public class ToggleStatus extends Communication {
private static String TAG = "ToggleStatus";
@Override
public String getCommand() {
String command = "setstatus:on"; | if (RemoteState.getInstance().getStatus() == RemoteState.Status.ON) { |
Hatzen/PrismatikRemote | app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/commands/ToggleMode.java | // Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/RemoteState.java
// public class RemoteState {
//
// public enum Status {
// ON,
// OFF,
// DEVICE_ERROR,
// UNKNOWN
// }
//
// public enum Mode {
// AMBILIGHT,
// MOODLAMP
// }
//
// private Status status = Status.UNKNOWN;
// private Mode mode = Mode.AMBILIGHT;
// private boolean statusApi;
// private ArrayList<String> profiles;
// private String profile;
// private int countLeds;
// private ArrayList<Rect> leds;
// private ArrayList<Integer> colors;
// private double gamma;
// private int brightness;
// private int smoothness;
//
// private static final RemoteState INSTANCE = new RemoteState();
//
// private RemoteState() {}
//
// public ArrayList<Integer> getColors() {
// return colors;
// }
//
// public void setColors(ArrayList<Integer> colors) {
// this.colors = colors;
// }
//
// public ArrayList<Rect> getLeds() {
// return leds;
// }
//
// public void setLeds(ArrayList<Rect> leds) {
// this.leds = leds;
// }
//
// public static RemoteState getInstance() {
// return INSTANCE;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public boolean isStatusApi() {
// return statusApi;
// }
//
// public void setStatusApi(boolean statusApi) {
// this.statusApi = statusApi;
// }
//
// public ArrayList<String> getProfiles() {
// return profiles;
// }
//
// public void setProfiles(ArrayList<String> profiles) {
// this.profiles = profiles;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public int getCountLeds() {
// return countLeds;
// }
//
// public void setCountLeds(int countLeds) {
// this.countLeds = countLeds;
// }
//
// public Mode getMode() {
// return mode;
// }
//
// public void setMode(Mode mode) {
// this.mode = mode;
// }
//
// public double getGamma() {
// return gamma;
// }
//
// public void setGamma(double gamma) {
// this.gamma = gamma;
// }
//
// public int getBrightness() {
// return brightness;
// }
//
// public void setBrightness(int brightness) {
// this.brightness = brightness;
// }
//
// public int getSmoothness() {
// return smoothness;
// }
//
// public void setSmoothness(int smoothness) {
// this.smoothness = smoothness;
// }
//
// }
| import de.prismatikremote.hartz.prismatikremote.backend.RemoteState; | package de.prismatikremote.hartz.prismatikremote.backend.commands;
/**
* Created by kaiha on 09.04.2017.
*/
public class ToggleMode extends Communication {
public static final String AMBILIGHT = "ambilight";
public static final String MOODLAMP = "moodlamp";
protected boolean needsDelay = true;
@Override
public String getCommand() {
String command = "setmode:"; | // Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/RemoteState.java
// public class RemoteState {
//
// public enum Status {
// ON,
// OFF,
// DEVICE_ERROR,
// UNKNOWN
// }
//
// public enum Mode {
// AMBILIGHT,
// MOODLAMP
// }
//
// private Status status = Status.UNKNOWN;
// private Mode mode = Mode.AMBILIGHT;
// private boolean statusApi;
// private ArrayList<String> profiles;
// private String profile;
// private int countLeds;
// private ArrayList<Rect> leds;
// private ArrayList<Integer> colors;
// private double gamma;
// private int brightness;
// private int smoothness;
//
// private static final RemoteState INSTANCE = new RemoteState();
//
// private RemoteState() {}
//
// public ArrayList<Integer> getColors() {
// return colors;
// }
//
// public void setColors(ArrayList<Integer> colors) {
// this.colors = colors;
// }
//
// public ArrayList<Rect> getLeds() {
// return leds;
// }
//
// public void setLeds(ArrayList<Rect> leds) {
// this.leds = leds;
// }
//
// public static RemoteState getInstance() {
// return INSTANCE;
// }
//
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// public boolean isStatusApi() {
// return statusApi;
// }
//
// public void setStatusApi(boolean statusApi) {
// this.statusApi = statusApi;
// }
//
// public ArrayList<String> getProfiles() {
// return profiles;
// }
//
// public void setProfiles(ArrayList<String> profiles) {
// this.profiles = profiles;
// }
//
// public String getProfile() {
// return profile;
// }
//
// public void setProfile(String profile) {
// this.profile = profile;
// }
//
// public int getCountLeds() {
// return countLeds;
// }
//
// public void setCountLeds(int countLeds) {
// this.countLeds = countLeds;
// }
//
// public Mode getMode() {
// return mode;
// }
//
// public void setMode(Mode mode) {
// this.mode = mode;
// }
//
// public double getGamma() {
// return gamma;
// }
//
// public void setGamma(double gamma) {
// this.gamma = gamma;
// }
//
// public int getBrightness() {
// return brightness;
// }
//
// public void setBrightness(int brightness) {
// this.brightness = brightness;
// }
//
// public int getSmoothness() {
// return smoothness;
// }
//
// public void setSmoothness(int smoothness) {
// this.smoothness = smoothness;
// }
//
// }
// Path: app/src/main/java/de/prismatikremote/hartz/prismatikremote/backend/commands/ToggleMode.java
import de.prismatikremote.hartz.prismatikremote.backend.RemoteState;
package de.prismatikremote.hartz.prismatikremote.backend.commands;
/**
* Created by kaiha on 09.04.2017.
*/
public class ToggleMode extends Communication {
public static final String AMBILIGHT = "ambilight";
public static final String MOODLAMP = "moodlamp";
protected boolean needsDelay = true;
@Override
public String getCommand() {
String command = "setmode:"; | if (RemoteState.getInstance().getMode() == RemoteState.Mode.AMBILIGHT) { |
Netcentric/vault-upgrade-hook | vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeInfoTest.java | // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
| import java.util.Arrays;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler; | Assert.assertNotNull(e);
}
sling.build().resource("/test", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER);
Node node = session.getNode("/test");
Mockito.when(ctx.getPackage().getId().getVersionString()).thenReturn("1.0.0");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertSame(node, info.getNode());
Assert.assertSame(status, info.getStatus());
Assert.assertEquals(UpgradeInfo.DEFAULT_INSTALLATION_MODE, info.getInstallationMode().toString());
Assert.assertEquals(UpgradeInfo.DEFAULT_PHASE, info.getDefaultPhase().toString());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertEquals(Phase.values().length, info.getActions().size());
UpgradeAction action = info.getActions().get(TestHandler.PHASE).get(0);
Assert.assertTrue(action instanceof UpgradeAction);
Assert.assertTrue(new MockUtil().isMock(action));
}
@Test
public void testConstructor() throws Exception {
sling.build().resource("/test", //
UpgradeInfo.PN_INSTALLATION_MODE, "always", //
UpgradeInfo.PN_DEFAULT_PHASE, "prepare", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER);
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
| // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
// Path: vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeInfoTest.java
import java.util.Arrays;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler;
Assert.assertNotNull(e);
}
sling.build().resource("/test", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER);
Node node = session.getNode("/test");
Mockito.when(ctx.getPackage().getId().getVersionString()).thenReturn("1.0.0");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertSame(node, info.getNode());
Assert.assertSame(status, info.getStatus());
Assert.assertEquals(UpgradeInfo.DEFAULT_INSTALLATION_MODE, info.getInstallationMode().toString());
Assert.assertEquals(UpgradeInfo.DEFAULT_PHASE, info.getDefaultPhase().toString());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertEquals(Phase.values().length, info.getActions().size());
UpgradeAction action = info.getActions().get(TestHandler.PHASE).get(0);
Assert.assertTrue(action instanceof UpgradeAction);
Assert.assertTrue(new MockUtil().isMock(action));
}
@Test
public void testConstructor() throws Exception {
sling.build().resource("/test", //
UpgradeInfo.PN_INSTALLATION_MODE, "always", //
UpgradeInfo.PN_DEFAULT_PHASE, "prepare", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER);
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
| Assert.assertEquals(InstallationMode.ALWAYS, info.getInstallationMode()); |
Netcentric/vault-upgrade-hook | vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeInfoTest.java | // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
| import java.util.Arrays;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler; | );
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertEquals(InstallationMode.ALWAYS, info.getInstallationMode());
Assert.assertEquals(Phase.PREPARE, info.getDefaultPhase());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertTrue(info.getRunModes().contains("publish"));
}
@Test
public void testConstructorWithRunModes() throws Exception {
sling.build().resource("/test", //
UpgradeInfo.PN_INSTALLATION_MODE, "always", //
UpgradeInfo.PN_DEFAULT_PHASE, "prepare", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER, //
UpgradeInfo.PN_RUNMODES, new String[] { "publish", "author" } //
);
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertEquals(InstallationMode.ALWAYS, info.getInstallationMode());
Assert.assertEquals(Phase.PREPARE, info.getDefaultPhase());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertTrue(info.getRunModes().contains("publish"));
Assert.assertTrue(info.getRunModes().contains("author"));
}
| // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
// Path: vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeInfoTest.java
import java.util.Arrays;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler;
);
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertEquals(InstallationMode.ALWAYS, info.getInstallationMode());
Assert.assertEquals(Phase.PREPARE, info.getDefaultPhase());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertTrue(info.getRunModes().contains("publish"));
}
@Test
public void testConstructorWithRunModes() throws Exception {
sling.build().resource("/test", //
UpgradeInfo.PN_INSTALLATION_MODE, "always", //
UpgradeInfo.PN_DEFAULT_PHASE, "prepare", //
UpgradeInfo.PN_HANDLER, TEST_HANDLER, //
UpgradeInfo.PN_RUNMODES, new String[] { "publish", "author" } //
);
Node node = session.getNode("/test");
UpgradeInfo info = new UpgradeInfo(ctx, status, node);
info.loadActions(ctx);
Assert.assertEquals(InstallationMode.ALWAYS, info.getInstallationMode());
Assert.assertEquals(Phase.PREPARE, info.getDefaultPhase());
Assert.assertTrue(info.getHandler() instanceof TestHandler);
Assert.assertTrue(info.getRunModes().contains("publish"));
Assert.assertTrue(info.getRunModes().contains("author"));
}
| public static class TestHandler implements UpgradeHandler { |
Netcentric/vault-upgrade-hook | vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeProcessorTest.java | // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
| import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.VaultPackage;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler; | /*
* (C) Copyright 2016 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.vlt.upgrade;
@RunWith(MockitoJUnitRunner.class)
public class UpgradeProcessorTest {
@Rule
public final SlingContext sling = new SlingContext(ResourceResolverType.JCR_MOCK);
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private InstallContext ctx;
@Mock
private VaultPackage vaultPackage;
@Mock
private UpgradeInfo info;
@Mock
private UpgradeAction action;
@Mock
private UpgradeStatus status;
private UpgradeProcessor processor;
@Before
public void setup() throws Exception {
processor = new UpgradeProcessor();
Mockito.when(ctx.getOptions()).thenReturn(Mockito.mock(ImportOptions.class));
Mockito.when(ctx.getSession()).thenReturn(sling.resourceResolver().adaptTo(Session.class));
Mockito.when(status.getNode()).thenReturn(Mockito.mock(Node.class));
Mockito.when(info.getNode()).thenReturn(Mockito.mock(Node.class)); | // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
// Path: vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeProcessorTest.java
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.VaultPackage;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler;
/*
* (C) Copyright 2016 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.vlt.upgrade;
@RunWith(MockitoJUnitRunner.class)
public class UpgradeProcessorTest {
@Rule
public final SlingContext sling = new SlingContext(ResourceResolverType.JCR_MOCK);
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private InstallContext ctx;
@Mock
private VaultPackage vaultPackage;
@Mock
private UpgradeInfo info;
@Mock
private UpgradeAction action;
@Mock
private UpgradeStatus status;
private UpgradeProcessor processor;
@Before
public void setup() throws Exception {
processor = new UpgradeProcessor();
Mockito.when(ctx.getOptions()).thenReturn(Mockito.mock(ImportOptions.class));
Mockito.when(ctx.getSession()).thenReturn(sling.resourceResolver().adaptTo(Session.class));
Mockito.when(status.getNode()).thenReturn(Mockito.mock(Node.class));
Mockito.when(info.getNode()).thenReturn(Mockito.mock(Node.class)); | Mockito.when(info.getHandler()).thenReturn(Mockito.mock(UpgradeHandler.class)); |
Netcentric/vault-upgrade-hook | vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeProcessorTest.java | // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
| import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.VaultPackage;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler; | Mockito.when(info.getExecutedActions()).thenReturn(Collections.<UpgradeAction>emptySet());
}
@Test
public void testExecutePrepare() throws Exception {
Mockito.when(ctx.getPhase()).thenReturn(Phase.PREPARE);
Mockito.when(ctx.getPackage().getId().getName()).thenReturn("testVaultPackage");
Mockito.when(ctx.getPackage().getId().getGroup()).thenReturn("testVaultGroup");
Mockito.when(ctx.getPackage().getId().getInstallationPath()).thenReturn("/test/installation/path");
Mockito.when(ctx.getPackage().getId().getVersionString()).thenReturn("1.0.1-SNAPSHOT");
sling.build().resource("/test/installation/path.zip/jcr:content/vlt:definition/upgrader/test", //
"handler", "biz.netcentric.vlt.upgrade.UpgradeProcessorTest$TestHandler" //
);
processor.execute(ctx);
Assert.assertEquals(1, processor.infos.size());
Assert.assertTrue(processor.infos.get(0).getHandler() instanceof TestHandler);
TestHandler handler = (TestHandler) processor.infos.get(0).getHandler();
Mockito.verify(handler.action).execute(ctx);
}
@Test
public void testExecuteInstalled() throws Exception {
Mockito.when(ctx.getPhase()).thenReturn(Phase.INSTALLED);
processor.infos = Arrays.asList(info);
Mockito.when(info.getActions()).thenReturn(Collections.singletonMap(Phase.INSTALLED, Arrays.asList(action)));
| // Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/UpgradeInfo.java
// public enum InstallationMode {
// /**
// * Run all new or changed actions.
// */
// ON_CHANGE,
//
// /**
// * Completely disregarding previous executions.
// */
// ALWAYS
// }
//
// Path: vault-upgrade-hook/src/main/java/biz/netcentric/vlt/upgrade/handler/UpgradeHandler.java
// public interface UpgradeHandler {
//
// /**
// * Is called to check if all requirements are met to create and run
// * {@link UpgradeAction}s provided by this handler.
// *
// * @return
// */
// boolean isAvailable(InstallContext ctx);
//
// /**
// * Called by {@link UpgradeInfo} to get the {@link UpgradeAction}s which are
// * configured in the content package.
// *
// * @param ctx
// * @param info
// * @return
// * @throws RepositoryException
// */
// Iterable<UpgradeAction> create(InstallContext ctx, UpgradeInfo info) throws RepositoryException;
//
// }
// Path: vault-upgrade-hook/src/test/java/biz/netcentric/vlt/upgrade/UpgradeProcessorTest.java
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.InstallContext.Phase;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.VaultPackage;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import biz.netcentric.vlt.upgrade.UpgradeInfo.InstallationMode;
import biz.netcentric.vlt.upgrade.handler.UpgradeHandler;
Mockito.when(info.getExecutedActions()).thenReturn(Collections.<UpgradeAction>emptySet());
}
@Test
public void testExecutePrepare() throws Exception {
Mockito.when(ctx.getPhase()).thenReturn(Phase.PREPARE);
Mockito.when(ctx.getPackage().getId().getName()).thenReturn("testVaultPackage");
Mockito.when(ctx.getPackage().getId().getGroup()).thenReturn("testVaultGroup");
Mockito.when(ctx.getPackage().getId().getInstallationPath()).thenReturn("/test/installation/path");
Mockito.when(ctx.getPackage().getId().getVersionString()).thenReturn("1.0.1-SNAPSHOT");
sling.build().resource("/test/installation/path.zip/jcr:content/vlt:definition/upgrader/test", //
"handler", "biz.netcentric.vlt.upgrade.UpgradeProcessorTest$TestHandler" //
);
processor.execute(ctx);
Assert.assertEquals(1, processor.infos.size());
Assert.assertTrue(processor.infos.get(0).getHandler() instanceof TestHandler);
TestHandler handler = (TestHandler) processor.infos.get(0).getHandler();
Mockito.verify(handler.action).execute(ctx);
}
@Test
public void testExecuteInstalled() throws Exception {
Mockito.when(ctx.getPhase()).thenReturn(Phase.INSTALLED);
processor.infos = Arrays.asList(info);
Mockito.when(info.getActions()).thenReturn(Collections.singletonMap(Phase.INSTALLED, Arrays.asList(action)));
| Mockito.when(info.getInstallationMode()).thenReturn(InstallationMode.ALWAYS); |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/DevAuthActivity.java | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth); | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/DevAuthActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth); | String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON); |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/DevAuthActivity.java | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) { | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/DevAuthActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) { | ZLog.logException(e); |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/DevAuthActivity.java | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter); | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/DevAuthActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
package com.zulip.android.activities;
/**
* Activity where the Emails for the DevAuthBackend are displayed.
*/
public class DevAuthActivity extends BaseActivity {
private RecyclerView recyclerView;
private CommonProgressDialog commonProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter); | authEmailAdapter.setOnItemClickListener(new AuthClickListener() { |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/DevAuthActivity.java | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter);
authEmailAdapter.setOnItemClickListener(new AuthClickListener() {
@Override
public void onItemClick(String email) {
commonProgressDialog.showWithMessage(getString(R.string.signing_in));
getServices()
.loginDEV(email) | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/DevAuthActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter);
authEmailAdapter.setOnItemClickListener(new AuthClickListener() {
@Override
public void onItemClick(String email) {
commonProgressDialog.showWithMessage(getString(R.string.signing_in));
getServices()
.loginDEV(email) | .enqueue(new DefaultCallback<LoginResponse>() { |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/DevAuthActivity.java | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response; | super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter);
authEmailAdapter.setOnItemClickListener(new AuthClickListener() {
@Override
public void onItemClick(String email) {
commonProgressDialog.showWithMessage(getString(R.string.signing_in));
getServices()
.loginDEV(email) | // Path: app/src/main/java/com/zulip/android/networking/AsyncDevGetEmails.java
// public class AsyncDevGetEmails extends ZulipAsyncPushTask {
// public final static String EMAIL_JSON = "emails_json";
// private static final String DISABLED = "dev_disabled";
// private Context context;
//
// public AsyncDevGetEmails(LoginActivity loginActivity) {
// super((ZulipApp) loginActivity.getApplication());
// context = loginActivity;
// }
//
// public final void execute() {
// execute("GET", "v1/dev_get_emails");
// }
//
// @Override
// protected void onPostExecute(String result) {
// try {
// JSONObject obj = new JSONObject(result);
// if (obj.getString("result").equals("success")) {
// Intent intent = new Intent(context, DevAuthActivity.class);
// intent.putExtra(EMAIL_JSON, result);
// context.startActivity(intent);
// ((LoginActivity) context).finish();
// }
// } catch (JSONException e) {
// ZLog.logException(e);
// }
// }
//
// @Override
// protected void onCancelled(String result) {
// super.onCancelled(result);
// if (result == null) return;
// String message = context.getString(R.string.network_error);
// try {
// JSONObject obj = new JSONObject(result);
// message = obj.getString("msg");
// } catch (JSONException e1) {
// ZLog.logException(e1);
// }
// final String finalMessage = message;
// ((LoginActivity) context).runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(context, finalMessage, Toast.LENGTH_LONG)
// .show();
// }
// });
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/response/LoginResponse.java
// public class LoginResponse {
//
// @SerializedName("msg")
// private String msg;
//
// @SerializedName("api_key")
// private String apiKey;
//
// @SerializedName("result")
// private String result;
//
// @SerializedName("email")
// private String email;
//
// public String getMsg() {
// return msg;
// }
//
// public String getApiKey() {
// return apiKey;
// }
//
// public String getResult() {
// return result;
// }
//
// public String getEmail() {
// return email;
// }
// }
//
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
// public abstract class DefaultCallback<T> implements Callback<T> {
//
// @Override
// @CallSuper
// public void onResponse(Call<T> call, Response<T> response) {
// if (response.isSuccessful()) {
// onSuccess(call, response);
// } else {
// onError(call, response);
// }
// }
//
// public abstract void onSuccess(Call<T> call, Response<T> response);
//
// public abstract void onError(Call<T> call, Response<T> response);
//
//
// @Override
// public void onFailure(Call<T> call, Throwable t) {
// //log error
// ZLog.logException(t);
// }
// }
//
// Path: app/src/main/java/com/zulip/android/util/AuthClickListener.java
// public interface AuthClickListener {
// void onItemClick(String email);
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/DevAuthActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.zulip.android.R;
import com.zulip.android.networking.AsyncDevGetEmails;
import com.zulip.android.networking.response.LoginResponse;
import com.zulip.android.networking.util.DefaultCallback;
import com.zulip.android.util.AuthClickListener;
import com.zulip.android.util.CommonProgressDialog;
import com.zulip.android.util.ZLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Response;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dev_auth);
String json = getIntent().getStringExtra(AsyncDevGetEmails.EMAIL_JSON);
recyclerView = (RecyclerView) findViewById(R.id.devAuthRecyclerView);
List<String> emails = new ArrayList<>();
int directAdminSize = 1;
commonProgressDialog = new CommonProgressDialog(this);
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("direct_admins");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
directAdminSize = jsonArray.length();
jsonArray = jsonObject.getJSONArray("direct_users");
for (int i = 0; i < jsonArray.length(); i++) {
emails.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
ZLog.logException(e);
}
AuthEmailAdapter authEmailAdapter = new AuthEmailAdapter(emails, directAdminSize, DevAuthActivity.this);
recyclerView.setAdapter(authEmailAdapter);
authEmailAdapter.setOnItemClickListener(new AuthClickListener() {
@Override
public void onItemClick(String email) {
commonProgressDialog.showWithMessage(getString(R.string.signing_in));
getServices()
.loginDEV(email) | .enqueue(new DefaultCallback<LoginResponse>() { |
zulip/zulip-android | app/src/main/java/com/zulip/android/networking/response/events/GetEventResponse.java | // Path: app/src/main/java/com/zulip/android/util/TypeSwapper.java
// public interface TypeSwapper<GIVEN, RETURN> {
// RETURN convert(GIVEN given);
//
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import com.zulip.android.util.TypeSwapper;
import com.zulip.android.util.ZLog;
import java.util.ArrayList;
import java.util.List; | package com.zulip.android.networking.response.events;
public class GetEventResponse {
@SerializedName("msg")
private String msg;
@SerializedName("result")
private String result;
@SerializedName("handler_id")
private int handlerId;
@SerializedName("events")
private List<EventsBranch> events;
@Nullable
public <T> List<T> getEventsOf(EventsBranch.BranchType branchType) {
return getEventsOf(branchType, null);
}
@Nullable | // Path: app/src/main/java/com/zulip/android/util/TypeSwapper.java
// public interface TypeSwapper<GIVEN, RETURN> {
// RETURN convert(GIVEN given);
//
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/networking/response/events/GetEventResponse.java
import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import com.zulip.android.util.TypeSwapper;
import com.zulip.android.util.ZLog;
import java.util.ArrayList;
import java.util.List;
package com.zulip.android.networking.response.events;
public class GetEventResponse {
@SerializedName("msg")
private String msg;
@SerializedName("result")
private String result;
@SerializedName("handler_id")
private int handlerId;
@SerializedName("events")
private List<EventsBranch> events;
@Nullable
public <T> List<T> getEventsOf(EventsBranch.BranchType branchType) {
return getEventsOf(branchType, null);
}
@Nullable | public <T extends EventsBranch, R> List<R> getEventsOf(EventsBranch.BranchType branchType, TypeSwapper<T, R> converter) { |
zulip/zulip-android | app/src/main/java/com/zulip/android/networking/response/events/GetEventResponse.java | // Path: app/src/main/java/com/zulip/android/util/TypeSwapper.java
// public interface TypeSwapper<GIVEN, RETURN> {
// RETURN convert(GIVEN given);
//
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import com.zulip.android.util.TypeSwapper;
import com.zulip.android.util.ZLog;
import java.util.ArrayList;
import java.util.List; | private int handlerId;
@SerializedName("events")
private List<EventsBranch> events;
@Nullable
public <T> List<T> getEventsOf(EventsBranch.BranchType branchType) {
return getEventsOf(branchType, null);
}
@Nullable
public <T extends EventsBranch, R> List<R> getEventsOf(EventsBranch.BranchType branchType, TypeSwapper<T, R> converter) {
if (events == null) {
return null;
}
try {
List<R> types = new ArrayList<>(events.size());
for (int i = 0; i < events.size(); i++) {
EventsBranch orig = events.get(i);
if (orig.getClass().equals(branchType.getKlazz())) {
if (converter != null) {
types.add(converter.convert((T) orig));
} else {
types.add((R) orig);
}
}
}
return types;
} catch (Exception e) {
//catch misuse | // Path: app/src/main/java/com/zulip/android/util/TypeSwapper.java
// public interface TypeSwapper<GIVEN, RETURN> {
// RETURN convert(GIVEN given);
//
// }
//
// Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/networking/response/events/GetEventResponse.java
import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import com.zulip.android.util.TypeSwapper;
import com.zulip.android.util.ZLog;
import java.util.ArrayList;
import java.util.List;
private int handlerId;
@SerializedName("events")
private List<EventsBranch> events;
@Nullable
public <T> List<T> getEventsOf(EventsBranch.BranchType branchType) {
return getEventsOf(branchType, null);
}
@Nullable
public <T extends EventsBranch, R> List<R> getEventsOf(EventsBranch.BranchType branchType, TypeSwapper<T, R> converter) {
if (events == null) {
return null;
}
try {
List<R> types = new ArrayList<>(events.size());
for (int i = 0; i < events.size(); i++) {
EventsBranch orig = events.get(i);
if (orig.getClass().equals(branchType.getKlazz())) {
if (converter != null) {
types.add(converter.convert((T) orig));
} else {
types.add((R) orig);
}
}
}
return types;
} catch (Exception e) {
//catch misuse | ZLog.logException(e); |
zulip/zulip-android | customlintjar/src/main/java/com/zulip/android/customlintrules/MyIssueRegistry.java | // Path: customlintjar/src/main/java/com/zulip/android/customlintrules/detectors/PrintStackTraceDetector.java
// public class PrintStackTraceDetector extends Detector
// implements Detector.ClassScanner {
//
// private static final Class<? extends Detector> DETECTOR_CLASS = PrintStackTraceDetector.class;
// private static final EnumSet<Scope> DETECTOR_SCOPE = Scope.CLASS_FILE_SCOPE;
//
// private static final Implementation IMPLEMENTATION = new Implementation(
// DETECTOR_CLASS,
// DETECTOR_SCOPE
// );
//
// private static final String ISSUE_ID = "ZLog";
// private static final String ISSUE_DESCRIPTION = "Use `ZLog.logException(e);` instead of `e.printStackTrace();` ";
// private static final String ISSUE_EXPLANATION = "`ZLog.logException(e);` print stacktrace as well as report that to the Crashlytics. " +
// "It provides real-time crash reporting, down to the exact line of code that caused the crash and we can start work as soon as it is reported. " +
// "All logged exceptions are appeared as 'non-fatal' issue in the Fabric dashboard. It helps in knowing when app gone to unexpected state like" +
// " malformed network data, misunderstanding of requirements, a logic error etc. Whenever exception is caught it prevent app to crash and continue the app flow(as well as report to Dashboard)";
// private static final Category ISSUE_CATEGORY = Category.USABILITY;
// private static final int ISSUE_PRIORITY = 9;
// private static final Severity ISSUE_SEVERITY = Severity.ERROR;
//
// public static final Issue ISSUE = Issue.create(
// ISSUE_ID,
// ISSUE_DESCRIPTION,
// ISSUE_EXPLANATION,
// ISSUE_CATEGORY,
// ISSUE_PRIORITY,
// ISSUE_SEVERITY,
// IMPLEMENTATION
// );
// private static final String FUNCTION_NAME = "printStackTrace";
//
// @Override
// public List<String> getApplicableCallNames() {
// return Collections.singletonList(FUNCTION_NAME);
// }
//
// @Override
// public List<String> getApplicableMethodNames() {
// return Collections.singletonList(FUNCTION_NAME);
// }
//
// @Override
// public void checkCall(@NonNull ClassContext context,
// @NonNull ClassNode classNode,
// @NonNull MethodNode method,
// @NonNull MethodInsnNode call) {
// context.report(ISSUE,
// method,
// call,
// context.getLocation(call),
// "You must use our `ZLog.logException(e);` ");
//
// }
// }
| import com.android.tools.lint.client.api.IssueRegistry;
import com.android.tools.lint.detector.api.Issue;
import com.zulip.android.customlintrules.detectors.PrintStackTraceDetector;
import java.util.Arrays;
import java.util.List; | package com.zulip.android.customlintrules;
@SuppressWarnings("unused")
public class MyIssueRegistry extends IssueRegistry {
@Override
public List<Issue> getIssues() {
System.out.println("********Working on custom lint check!!!********");
return Arrays.asList( | // Path: customlintjar/src/main/java/com/zulip/android/customlintrules/detectors/PrintStackTraceDetector.java
// public class PrintStackTraceDetector extends Detector
// implements Detector.ClassScanner {
//
// private static final Class<? extends Detector> DETECTOR_CLASS = PrintStackTraceDetector.class;
// private static final EnumSet<Scope> DETECTOR_SCOPE = Scope.CLASS_FILE_SCOPE;
//
// private static final Implementation IMPLEMENTATION = new Implementation(
// DETECTOR_CLASS,
// DETECTOR_SCOPE
// );
//
// private static final String ISSUE_ID = "ZLog";
// private static final String ISSUE_DESCRIPTION = "Use `ZLog.logException(e);` instead of `e.printStackTrace();` ";
// private static final String ISSUE_EXPLANATION = "`ZLog.logException(e);` print stacktrace as well as report that to the Crashlytics. " +
// "It provides real-time crash reporting, down to the exact line of code that caused the crash and we can start work as soon as it is reported. " +
// "All logged exceptions are appeared as 'non-fatal' issue in the Fabric dashboard. It helps in knowing when app gone to unexpected state like" +
// " malformed network data, misunderstanding of requirements, a logic error etc. Whenever exception is caught it prevent app to crash and continue the app flow(as well as report to Dashboard)";
// private static final Category ISSUE_CATEGORY = Category.USABILITY;
// private static final int ISSUE_PRIORITY = 9;
// private static final Severity ISSUE_SEVERITY = Severity.ERROR;
//
// public static final Issue ISSUE = Issue.create(
// ISSUE_ID,
// ISSUE_DESCRIPTION,
// ISSUE_EXPLANATION,
// ISSUE_CATEGORY,
// ISSUE_PRIORITY,
// ISSUE_SEVERITY,
// IMPLEMENTATION
// );
// private static final String FUNCTION_NAME = "printStackTrace";
//
// @Override
// public List<String> getApplicableCallNames() {
// return Collections.singletonList(FUNCTION_NAME);
// }
//
// @Override
// public List<String> getApplicableMethodNames() {
// return Collections.singletonList(FUNCTION_NAME);
// }
//
// @Override
// public void checkCall(@NonNull ClassContext context,
// @NonNull ClassNode classNode,
// @NonNull MethodNode method,
// @NonNull MethodInsnNode call) {
// context.report(ISSUE,
// method,
// call,
// context.getLocation(call),
// "You must use our `ZLog.logException(e);` ");
//
// }
// }
// Path: customlintjar/src/main/java/com/zulip/android/customlintrules/MyIssueRegistry.java
import com.android.tools.lint.client.api.IssueRegistry;
import com.android.tools.lint.detector.api.Issue;
import com.zulip.android.customlintrules.detectors.PrintStackTraceDetector;
import java.util.Arrays;
import java.util.List;
package com.zulip.android.customlintrules;
@SuppressWarnings("unused")
public class MyIssueRegistry extends IssueRegistry {
@Override
public List<Issue> getIssues() {
System.out.println("********Working on custom lint check!!!********");
return Arrays.asList( | PrintStackTraceDetector.ISSUE); |
zulip/zulip-android | app/src/main/java/com/zulip/android/networking/response/events/ReactionWrapper.java | // Path: app/src/main/java/com/zulip/android/models/Reaction.java
// @DatabaseTable(tableName = "reactions")
// public class Reaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String USER_FIELD = "user";
// private static final String MESSAGE_FIELD = "message";
//
//
// @SerializedName("emoji_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String emojiName;
//
// @SerializedName("user")
// @DatabaseField(foreign = true, columnName = USER_FIELD)
// private UserReaction user;
//
// @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = MESSAGE_FIELD)
// private Message message;
//
//
// /**
// * Construct an empty Reaction object.
// */
// public Reaction() {
//
// }
//
// public String getEmoji() {
// return this.emojiName;
// }
//
// public void setEmoji(String name) {
// this.emojiName = name;
// }
//
// public UserReaction getUser() {
// return this.user;
// }
//
// public void setUser(UserReaction user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ":" + getEmoji() + ":";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Reaction) {
// Reaction reaction = (Reaction) obj;
// return this.emojiName.equals(reaction.emojiName) && this.user.equals(reaction.user);
// } else {
// return false;
// }
// }
// }
//
// Path: app/src/main/java/com/zulip/android/models/UserReaction.java
// @DatabaseTable(tableName = "reactions_user")
// public class UserReaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String EMAIL_FIELD = "email";
//
// @SerializedName("id")
// @DatabaseField(id = true, columnName = ID_FIELD)
// private int id;
//
// @SerializedName("full_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String name;
//
// @SerializedName("email")
// @DatabaseField(columnName = EMAIL_FIELD)
// private String email;
//
// /**
// * Used in reaction type event {@link com.zulip.android.networking.response.events.ReactionWrapper}
// */
// @SerializedName("user_id")
// private int alternateId;
//
// /**
// * Construct an empty User object.
// */
// public UserReaction() {
//
// }
//
//
// public int getId() {
// return this.id;
// }
//
// public String getName() {
// return this.name;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public int getAlternateId() {
// return this.alternateId;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserReaction) {
// UserReaction user = (UserReaction) obj;
// return this.getId() == user.getId();
// } else {
// return false;
// }
// }
// }
| import com.google.gson.annotations.SerializedName;
import com.zulip.android.models.Reaction;
import com.zulip.android.models.UserReaction; | package com.zulip.android.networking.response.events;
/**
* This class is used to deserialize the reaction type event {@link EventsBranch.BranchType#REACTION}
* example: {"emoji_name":"alarm_clock","id":54,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"add"}
* {"emoji_name":"alarm_clock","id":72,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"remove"}
*/
public class ReactionWrapper extends EventsBranch {
public static final String OPERATION_ADD = "add";
public static final String OPERATION_REMOVE = "remove";
@SerializedName("emoji_name")
private String emoji;
@SerializedName("user") | // Path: app/src/main/java/com/zulip/android/models/Reaction.java
// @DatabaseTable(tableName = "reactions")
// public class Reaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String USER_FIELD = "user";
// private static final String MESSAGE_FIELD = "message";
//
//
// @SerializedName("emoji_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String emojiName;
//
// @SerializedName("user")
// @DatabaseField(foreign = true, columnName = USER_FIELD)
// private UserReaction user;
//
// @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = MESSAGE_FIELD)
// private Message message;
//
//
// /**
// * Construct an empty Reaction object.
// */
// public Reaction() {
//
// }
//
// public String getEmoji() {
// return this.emojiName;
// }
//
// public void setEmoji(String name) {
// this.emojiName = name;
// }
//
// public UserReaction getUser() {
// return this.user;
// }
//
// public void setUser(UserReaction user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ":" + getEmoji() + ":";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Reaction) {
// Reaction reaction = (Reaction) obj;
// return this.emojiName.equals(reaction.emojiName) && this.user.equals(reaction.user);
// } else {
// return false;
// }
// }
// }
//
// Path: app/src/main/java/com/zulip/android/models/UserReaction.java
// @DatabaseTable(tableName = "reactions_user")
// public class UserReaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String EMAIL_FIELD = "email";
//
// @SerializedName("id")
// @DatabaseField(id = true, columnName = ID_FIELD)
// private int id;
//
// @SerializedName("full_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String name;
//
// @SerializedName("email")
// @DatabaseField(columnName = EMAIL_FIELD)
// private String email;
//
// /**
// * Used in reaction type event {@link com.zulip.android.networking.response.events.ReactionWrapper}
// */
// @SerializedName("user_id")
// private int alternateId;
//
// /**
// * Construct an empty User object.
// */
// public UserReaction() {
//
// }
//
//
// public int getId() {
// return this.id;
// }
//
// public String getName() {
// return this.name;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public int getAlternateId() {
// return this.alternateId;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserReaction) {
// UserReaction user = (UserReaction) obj;
// return this.getId() == user.getId();
// } else {
// return false;
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/networking/response/events/ReactionWrapper.java
import com.google.gson.annotations.SerializedName;
import com.zulip.android.models.Reaction;
import com.zulip.android.models.UserReaction;
package com.zulip.android.networking.response.events;
/**
* This class is used to deserialize the reaction type event {@link EventsBranch.BranchType#REACTION}
* example: {"emoji_name":"alarm_clock","id":54,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"add"}
* {"emoji_name":"alarm_clock","id":72,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"remove"}
*/
public class ReactionWrapper extends EventsBranch {
public static final String OPERATION_ADD = "add";
public static final String OPERATION_REMOVE = "remove";
@SerializedName("emoji_name")
private String emoji;
@SerializedName("user") | private UserReaction user; |
zulip/zulip-android | app/src/main/java/com/zulip/android/networking/response/events/ReactionWrapper.java | // Path: app/src/main/java/com/zulip/android/models/Reaction.java
// @DatabaseTable(tableName = "reactions")
// public class Reaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String USER_FIELD = "user";
// private static final String MESSAGE_FIELD = "message";
//
//
// @SerializedName("emoji_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String emojiName;
//
// @SerializedName("user")
// @DatabaseField(foreign = true, columnName = USER_FIELD)
// private UserReaction user;
//
// @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = MESSAGE_FIELD)
// private Message message;
//
//
// /**
// * Construct an empty Reaction object.
// */
// public Reaction() {
//
// }
//
// public String getEmoji() {
// return this.emojiName;
// }
//
// public void setEmoji(String name) {
// this.emojiName = name;
// }
//
// public UserReaction getUser() {
// return this.user;
// }
//
// public void setUser(UserReaction user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ":" + getEmoji() + ":";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Reaction) {
// Reaction reaction = (Reaction) obj;
// return this.emojiName.equals(reaction.emojiName) && this.user.equals(reaction.user);
// } else {
// return false;
// }
// }
// }
//
// Path: app/src/main/java/com/zulip/android/models/UserReaction.java
// @DatabaseTable(tableName = "reactions_user")
// public class UserReaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String EMAIL_FIELD = "email";
//
// @SerializedName("id")
// @DatabaseField(id = true, columnName = ID_FIELD)
// private int id;
//
// @SerializedName("full_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String name;
//
// @SerializedName("email")
// @DatabaseField(columnName = EMAIL_FIELD)
// private String email;
//
// /**
// * Used in reaction type event {@link com.zulip.android.networking.response.events.ReactionWrapper}
// */
// @SerializedName("user_id")
// private int alternateId;
//
// /**
// * Construct an empty User object.
// */
// public UserReaction() {
//
// }
//
//
// public int getId() {
// return this.id;
// }
//
// public String getName() {
// return this.name;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public int getAlternateId() {
// return this.alternateId;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserReaction) {
// UserReaction user = (UserReaction) obj;
// return this.getId() == user.getId();
// } else {
// return false;
// }
// }
// }
| import com.google.gson.annotations.SerializedName;
import com.zulip.android.models.Reaction;
import com.zulip.android.models.UserReaction; | package com.zulip.android.networking.response.events;
/**
* This class is used to deserialize the reaction type event {@link EventsBranch.BranchType#REACTION}
* example: {"emoji_name":"alarm_clock","id":54,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"add"}
* {"emoji_name":"alarm_clock","id":72,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"remove"}
*/
public class ReactionWrapper extends EventsBranch {
public static final String OPERATION_ADD = "add";
public static final String OPERATION_REMOVE = "remove";
@SerializedName("emoji_name")
private String emoji;
@SerializedName("user")
private UserReaction user;
@SerializedName("message_id")
private int messageId;
@SerializedName("op")
private String operation;
public ReactionWrapper() {
}
public int getMessageId() {
return this.messageId;
}
| // Path: app/src/main/java/com/zulip/android/models/Reaction.java
// @DatabaseTable(tableName = "reactions")
// public class Reaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String USER_FIELD = "user";
// private static final String MESSAGE_FIELD = "message";
//
//
// @SerializedName("emoji_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String emojiName;
//
// @SerializedName("user")
// @DatabaseField(foreign = true, columnName = USER_FIELD)
// private UserReaction user;
//
// @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = MESSAGE_FIELD)
// private Message message;
//
//
// /**
// * Construct an empty Reaction object.
// */
// public Reaction() {
//
// }
//
// public String getEmoji() {
// return this.emojiName;
// }
//
// public void setEmoji(String name) {
// this.emojiName = name;
// }
//
// public UserReaction getUser() {
// return this.user;
// }
//
// public void setUser(UserReaction user) {
// this.user = user;
// }
//
// @Override
// public String toString() {
// return ":" + getEmoji() + ":";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Reaction) {
// Reaction reaction = (Reaction) obj;
// return this.emojiName.equals(reaction.emojiName) && this.user.equals(reaction.user);
// } else {
// return false;
// }
// }
// }
//
// Path: app/src/main/java/com/zulip/android/models/UserReaction.java
// @DatabaseTable(tableName = "reactions_user")
// public class UserReaction {
// private static final String ID_FIELD = "id";
// private static final String NAME_FIELD = "name";
// private static final String EMAIL_FIELD = "email";
//
// @SerializedName("id")
// @DatabaseField(id = true, columnName = ID_FIELD)
// private int id;
//
// @SerializedName("full_name")
// @DatabaseField(columnName = NAME_FIELD)
// private String name;
//
// @SerializedName("email")
// @DatabaseField(columnName = EMAIL_FIELD)
// private String email;
//
// /**
// * Used in reaction type event {@link com.zulip.android.networking.response.events.ReactionWrapper}
// */
// @SerializedName("user_id")
// private int alternateId;
//
// /**
// * Construct an empty User object.
// */
// public UserReaction() {
//
// }
//
//
// public int getId() {
// return this.id;
// }
//
// public String getName() {
// return this.name;
// }
//
// public String getEmail() {
// return this.email;
// }
//
// public int getAlternateId() {
// return this.alternateId;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof UserReaction) {
// UserReaction user = (UserReaction) obj;
// return this.getId() == user.getId();
// } else {
// return false;
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/networking/response/events/ReactionWrapper.java
import com.google.gson.annotations.SerializedName;
import com.zulip.android.models.Reaction;
import com.zulip.android.models.UserReaction;
package com.zulip.android.networking.response.events;
/**
* This class is used to deserialize the reaction type event {@link EventsBranch.BranchType#REACTION}
* example: {"emoji_name":"alarm_clock","id":54,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"add"}
* {"emoji_name":"alarm_clock","id":72,"user":{"user_id":346,"email":"abc@gmail.com","full_name":"anonymous user"},"type":"reaction","message_id":163213,"op":"remove"}
*/
public class ReactionWrapper extends EventsBranch {
public static final String OPERATION_ADD = "add";
public static final String OPERATION_REMOVE = "remove";
@SerializedName("emoji_name")
private String emoji;
@SerializedName("user")
private UserReaction user;
@SerializedName("message_id")
private int messageId;
@SerializedName("op")
private String operation;
public ReactionWrapper() {
}
public int getMessageId() {
return this.messageId;
}
| public Reaction getReaction() { |
zulip/zulip-android | app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java | // Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
| import android.support.annotation.CallSuper;
import com.zulip.android.util.ZLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | package com.zulip.android.networking.util;
public abstract class DefaultCallback<T> implements Callback<T> {
@Override
@CallSuper
public void onResponse(Call<T> call, Response<T> response) {
if (response.isSuccessful()) {
onSuccess(call, response);
} else {
onError(call, response);
}
}
public abstract void onSuccess(Call<T> call, Response<T> response);
public abstract void onError(Call<T> call, Response<T> response);
@Override
public void onFailure(Call<T> call, Throwable t) {
//log error | // Path: app/src/main/java/com/zulip/android/util/ZLog.java
// public class ZLog {
//
// private ZLog() {
// }
//
// public static void logException(Throwable e) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", "oops", e);
// } else {
// Crashlytics.logException(e);
// }
// }
//
// public static void log(String message) {
// if (!BuildHelper.shouldLogToCrashlytics()) {
// Log.e("Error", message);
// } else {
// Crashlytics.log(message);
// }
// }
// }
// Path: app/src/main/java/com/zulip/android/networking/util/DefaultCallback.java
import android.support.annotation.CallSuper;
import com.zulip.android.util.ZLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
package com.zulip.android.networking.util;
public abstract class DefaultCallback<T> implements Callback<T> {
@Override
@CallSuper
public void onResponse(Call<T> call, Response<T> response) {
if (response.isSuccessful()) {
onSuccess(call, response);
} else {
onError(call, response);
}
}
public abstract void onSuccess(Call<T> call, Response<T> response);
public abstract void onError(Call<T> call, Response<T> response);
@Override
public void onFailure(Call<T> call, Throwable t) {
//log error | ZLog.logException(t); |
zulip/zulip-android | app/src/main/java/com/zulip/android/filters/NarrowFilterSearch.java | // Path: app/src/main/java/com/zulip/android/database/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
//
// // name of the database file for your application -- change to something
// // appropriate for your app
// private static final String DATABASE_NAME = "zulip-%s.db";
// // any time you make changes to your database objects, you may have to
// // increase the database version
// private static final int DATABASE_VERSION = 11;
//
// public DatabaseHelper(ZulipApp app, String email) {
// super(app, String.format(DATABASE_NAME, MD5Util.md5Hex(email)), null,
// DATABASE_VERSION, R.raw.ormlite_config);
// }
//
// /**
// * Escape LIKE wildcards with a backslash. Must also use ESCAPE clause
// *
// * @param likeClause string to escape
// * @return Escaped string
// */
// public static String likeEscape(String likeClause) {
// return likeClause.replace("%", "\\%").replace("_", "\\_");
// }
//
// /**
// * This is called when the database is first created. Usually you should
// * call createTable statements here to create the tables that will store
// * your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// Log.i(DatabaseHelper.class.getName(), "onCreate");
// // Create the databases we're using
// TableUtils.createTable(connectionSource, Person.class);
// TableUtils.createTable(connectionSource, Stream.class);
// TableUtils.createTable(connectionSource, Message.class);
// TableUtils.createTable(connectionSource, MessageRange.class);
// TableUtils.createTable(connectionSource, Emoji.class);
// TableUtils.createTable(connectionSource, Reaction.class);
// TableUtils.createTable(connectionSource, UserReaction.class);
// } catch (SQLException e) {
// Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// public void resetDatabase(SQLiteDatabase db) {
// ZulipApp.get().onResetDatabase();
// Log.i("resetDatabase", "Resetting database");
//
// boolean inTransaction = db.inTransaction();
//
// if (!inTransaction) {
// db.beginTransaction();
// }
//
// Cursor c = db.rawQuery(
// "SELECT name FROM sqlite_master WHERE type='table'"
// + "AND name NOT LIKE 'sqlite_%'"
// + "AND name NOT LIKE 'android_%';", null);
// while (c.moveToNext()) {
// String name = c.getString(0);
// Log.i("resetDatabase", "Dropping " + name);
// db.execSQL("DROP TABLE " + name);
// }
//
// c.close();
//
// db.setTransactionSuccessful();
// db.endTransaction();
// db.execSQL("VACUUM;");
//
// if (inTransaction) {
// db.beginTransaction();
// }
//
// onCreate(db);
// }
//
// /**
// * This is called when your application is upgraded and it has a higher
// * version number. This allows you to adjust the various data to match the
// * new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
// int oldVersion, int newVersion) {
// resetDatabase(db);
// }
//
// @Override
// public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// resetDatabase(db);
// }
// }
| import android.os.Parcel;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.stmt.Where;
import com.zulip.android.database.DatabaseHelper;
import com.zulip.android.models.Message;
import com.zulip.android.models.Stream;
import org.json.JSONArray;
import org.json.JSONException;
import java.sql.SQLException;
import java.util.Arrays; | package com.zulip.android.filters;
/**
* Narrow based on search terms
* {@link NarrowFilterSearch#query} is the search query
* {@link NarrowFilterSearch#filter} indicates the current narrow filter
*/
public class NarrowFilterSearch implements NarrowFilter {
public static final Creator<NarrowFilterSearch> CREATOR = new Creator<NarrowFilterSearch>() {
@Override
public NarrowFilterSearch createFromParcel(Parcel parcel) {
return new NarrowFilterSearch(parcel.readString(), null);
}
@Override
public NarrowFilterSearch[] newArray(int i) {
return new NarrowFilterSearch[i];
}
};
private String query;
private NarrowFilter filter;
public NarrowFilterSearch(String query, NarrowFilter filter) {
this.query = query;
this.filter = filter;
}
@Override
public Where<Message, Object> modWhere(Where<Message, Object> where)
throws SQLException {
where.raw(
Message.CONTENT_FIELD + " LIKE ? COLLATE NOCASE",
new SelectArg(Message.CONTENT_FIELD, "%" | // Path: app/src/main/java/com/zulip/android/database/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
//
// // name of the database file for your application -- change to something
// // appropriate for your app
// private static final String DATABASE_NAME = "zulip-%s.db";
// // any time you make changes to your database objects, you may have to
// // increase the database version
// private static final int DATABASE_VERSION = 11;
//
// public DatabaseHelper(ZulipApp app, String email) {
// super(app, String.format(DATABASE_NAME, MD5Util.md5Hex(email)), null,
// DATABASE_VERSION, R.raw.ormlite_config);
// }
//
// /**
// * Escape LIKE wildcards with a backslash. Must also use ESCAPE clause
// *
// * @param likeClause string to escape
// * @return Escaped string
// */
// public static String likeEscape(String likeClause) {
// return likeClause.replace("%", "\\%").replace("_", "\\_");
// }
//
// /**
// * This is called when the database is first created. Usually you should
// * call createTable statements here to create the tables that will store
// * your data.
// */
// @Override
// public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
// try {
// Log.i(DatabaseHelper.class.getName(), "onCreate");
// // Create the databases we're using
// TableUtils.createTable(connectionSource, Person.class);
// TableUtils.createTable(connectionSource, Stream.class);
// TableUtils.createTable(connectionSource, Message.class);
// TableUtils.createTable(connectionSource, MessageRange.class);
// TableUtils.createTable(connectionSource, Emoji.class);
// TableUtils.createTable(connectionSource, Reaction.class);
// TableUtils.createTable(connectionSource, UserReaction.class);
// } catch (SQLException e) {
// Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
// throw new RuntimeException(e);
// }
// }
//
// public void resetDatabase(SQLiteDatabase db) {
// ZulipApp.get().onResetDatabase();
// Log.i("resetDatabase", "Resetting database");
//
// boolean inTransaction = db.inTransaction();
//
// if (!inTransaction) {
// db.beginTransaction();
// }
//
// Cursor c = db.rawQuery(
// "SELECT name FROM sqlite_master WHERE type='table'"
// + "AND name NOT LIKE 'sqlite_%'"
// + "AND name NOT LIKE 'android_%';", null);
// while (c.moveToNext()) {
// String name = c.getString(0);
// Log.i("resetDatabase", "Dropping " + name);
// db.execSQL("DROP TABLE " + name);
// }
//
// c.close();
//
// db.setTransactionSuccessful();
// db.endTransaction();
// db.execSQL("VACUUM;");
//
// if (inTransaction) {
// db.beginTransaction();
// }
//
// onCreate(db);
// }
//
// /**
// * This is called when your application is upgraded and it has a higher
// * version number. This allows you to adjust the various data to match the
// * new version number.
// */
// @Override
// public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
// int oldVersion, int newVersion) {
// resetDatabase(db);
// }
//
// @Override
// public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// resetDatabase(db);
// }
// }
// Path: app/src/main/java/com/zulip/android/filters/NarrowFilterSearch.java
import android.os.Parcel;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.stmt.Where;
import com.zulip.android.database.DatabaseHelper;
import com.zulip.android.models.Message;
import com.zulip.android.models.Stream;
import org.json.JSONArray;
import org.json.JSONException;
import java.sql.SQLException;
import java.util.Arrays;
package com.zulip.android.filters;
/**
* Narrow based on search terms
* {@link NarrowFilterSearch#query} is the search query
* {@link NarrowFilterSearch#filter} indicates the current narrow filter
*/
public class NarrowFilterSearch implements NarrowFilter {
public static final Creator<NarrowFilterSearch> CREATOR = new Creator<NarrowFilterSearch>() {
@Override
public NarrowFilterSearch createFromParcel(Parcel parcel) {
return new NarrowFilterSearch(parcel.readString(), null);
}
@Override
public NarrowFilterSearch[] newArray(int i) {
return new NarrowFilterSearch[i];
}
};
private String query;
private NarrowFilter filter;
public NarrowFilterSearch(String query, NarrowFilter filter) {
this.query = query;
this.filter = filter;
}
@Override
public Where<Message, Object> modWhere(Where<Message, Object> where)
throws SQLException {
where.raw(
Message.CONTENT_FIELD + " LIKE ? COLLATE NOCASE",
new SelectArg(Message.CONTENT_FIELD, "%" | + DatabaseHelper.likeEscape(query) + "%")); |
zulip/zulip-android | app/src/main/java/com/zulip/android/activities/PhotoSendActivity.java | // Path: app/src/main/java/com/zulip/android/util/PhotoHelper.java
// public class PhotoHelper {
//
// /**
// * Function to delete the file at {@param photoPath} and store {@param bitmap}
// * at {@param photoPath}.
// *
// * @param photoPath file path
// * @param bitmap to be saved as file
// */
// public static String saveBitmapAsFile(String photoPath, Bitmap bitmap) {
// if (bitmap == null) {
// return photoPath;
// }
//
// // delete old bitmap
// File file = new File(photoPath);
// file.delete();
//
// // store new bitmap at mPhotoPath file path
// FileOutputStream out = null;
// try {
// // change file name to avoid catching issues with Glide
// int position = photoPath.lastIndexOf(".");
// photoPath = photoPath.substring(0, position) + Math.round(Math.random() * 10)
// + photoPath.substring(position);
//
// out = new FileOutputStream(photoPath);
//
// // bmp is your Bitmap instance
// // PNG is a lossless format, the compression factor (100) is ignored
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// } catch (Exception e) {
// ZLog.logException(e);
// } finally {
// try {
// if (out != null) {
// out.close();
// }
// } catch (IOException e) {
// ZLog.logException(e);
// }
// }
//
// return photoPath;
// }
//
// /**
// * From http://stackoverflow.com/a/26930938/5334314
// * Returns the actual bitmap position in an imageView.
// *
// * @param imageView source ImageView
// * @return 0: left, 1: top, 2: width, 3: height
// */
// public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
// int[] ret = new int[4];
//
// if (imageView == null || imageView.getDrawable() == null) {
// return ret;
// }
//
// // Get image dimensions
// // Get image matrix values and place them in an array
// float[] f = new float[9];
// imageView.getImageMatrix().getValues(f);
//
// // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
// final float scaleX = f[Matrix.MSCALE_X];
// final float scaleY = f[Matrix.MSCALE_Y];
//
// // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
// final Drawable d = imageView.getDrawable();
// final int origW = d.getIntrinsicWidth();
// final int origH = d.getIntrinsicHeight();
//
// // Calculate the actual dimensions
// final int actW = Math.round(origW * scaleX);
// final int actH = Math.round(origH * scaleY);
//
// ret[2] = actW;
// ret[3] = actH;
//
// // Get image position
// // We assume that the image is centered into ImageView
// int imgViewW = imageView.getWidth();
// int imgViewH = imageView.getHeight();
//
// int top = (int) (imgViewH - actH) / 2;
// int left = (int) (imgViewW - actW) / 2;
//
// ret[0] = left;
// ret[1] = top;
//
// return ret;
// }
// }
| import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.zulip.android.R;
import com.zulip.android.util.ActivityTransitionAnim;
import com.zulip.android.util.PhotoHelper;
import java.io.File; | // tint the crop button white when cropping is finished
mCropBtn.setColorFilter(Color.WHITE);
mIsCropFinished = false;
}
}
});
ImageView sendPhoto = (ImageView) findViewById(R.id.send_photo);
sendPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bitmap;
Drawable drawable = mImageView.getDrawable();
if (drawable instanceof GlideBitmapDrawable) {
// if imageview has drawable of type GlideBitmapDrawable
bitmap = ((GlideBitmapDrawable) mImageView.getDrawable().getCurrent())
.getBitmap();
} else {
// if imageView stores cropped image drawable which is of type drawable
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
}
/* Most phone cameras are landscape, meaning if you take the photo in portrait,
the resulting photos will be rotated 90 degrees. Hence used the displayed image
with correct orientation and saved that in the current photo path.
*/
// delete old file and store new bitmap on that location
// used the displayed image and saved it in the mPhotoPath | // Path: app/src/main/java/com/zulip/android/util/PhotoHelper.java
// public class PhotoHelper {
//
// /**
// * Function to delete the file at {@param photoPath} and store {@param bitmap}
// * at {@param photoPath}.
// *
// * @param photoPath file path
// * @param bitmap to be saved as file
// */
// public static String saveBitmapAsFile(String photoPath, Bitmap bitmap) {
// if (bitmap == null) {
// return photoPath;
// }
//
// // delete old bitmap
// File file = new File(photoPath);
// file.delete();
//
// // store new bitmap at mPhotoPath file path
// FileOutputStream out = null;
// try {
// // change file name to avoid catching issues with Glide
// int position = photoPath.lastIndexOf(".");
// photoPath = photoPath.substring(0, position) + Math.round(Math.random() * 10)
// + photoPath.substring(position);
//
// out = new FileOutputStream(photoPath);
//
// // bmp is your Bitmap instance
// // PNG is a lossless format, the compression factor (100) is ignored
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// } catch (Exception e) {
// ZLog.logException(e);
// } finally {
// try {
// if (out != null) {
// out.close();
// }
// } catch (IOException e) {
// ZLog.logException(e);
// }
// }
//
// return photoPath;
// }
//
// /**
// * From http://stackoverflow.com/a/26930938/5334314
// * Returns the actual bitmap position in an imageView.
// *
// * @param imageView source ImageView
// * @return 0: left, 1: top, 2: width, 3: height
// */
// public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
// int[] ret = new int[4];
//
// if (imageView == null || imageView.getDrawable() == null) {
// return ret;
// }
//
// // Get image dimensions
// // Get image matrix values and place them in an array
// float[] f = new float[9];
// imageView.getImageMatrix().getValues(f);
//
// // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
// final float scaleX = f[Matrix.MSCALE_X];
// final float scaleY = f[Matrix.MSCALE_Y];
//
// // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
// final Drawable d = imageView.getDrawable();
// final int origW = d.getIntrinsicWidth();
// final int origH = d.getIntrinsicHeight();
//
// // Calculate the actual dimensions
// final int actW = Math.round(origW * scaleX);
// final int actH = Math.round(origH * scaleY);
//
// ret[2] = actW;
// ret[3] = actH;
//
// // Get image position
// // We assume that the image is centered into ImageView
// int imgViewW = imageView.getWidth();
// int imgViewH = imageView.getHeight();
//
// int top = (int) (imgViewH - actH) / 2;
// int left = (int) (imgViewW - actW) / 2;
//
// ret[0] = left;
// ret[1] = top;
//
// return ret;
// }
// }
// Path: app/src/main/java/com/zulip/android/activities/PhotoSendActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.zulip.android.R;
import com.zulip.android.util.ActivityTransitionAnim;
import com.zulip.android.util.PhotoHelper;
import java.io.File;
// tint the crop button white when cropping is finished
mCropBtn.setColorFilter(Color.WHITE);
mIsCropFinished = false;
}
}
});
ImageView sendPhoto = (ImageView) findViewById(R.id.send_photo);
sendPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bitmap;
Drawable drawable = mImageView.getDrawable();
if (drawable instanceof GlideBitmapDrawable) {
// if imageview has drawable of type GlideBitmapDrawable
bitmap = ((GlideBitmapDrawable) mImageView.getDrawable().getCurrent())
.getBitmap();
} else {
// if imageView stores cropped image drawable which is of type drawable
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
}
/* Most phone cameras are landscape, meaning if you take the photo in portrait,
the resulting photos will be rotated 90 degrees. Hence used the displayed image
with correct orientation and saved that in the current photo path.
*/
// delete old file and store new bitmap on that location
// used the displayed image and saved it in the mPhotoPath | mPhotoPath = PhotoHelper.saveBitmapAsFile(mPhotoPath, bitmap); |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/view/OpenWebSocketView.java | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
| import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;
import org.erlymon.monitor.mvp.model.Event; | /*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.mvp.view;
/**
* Created by sergey on 17.03.17.
*/
@StateStrategyType(AddToEndSingleStrategy.class)
public interface OpenWebSocketView extends MvpView {
void startOpenWebSocket();
void finishOpenWebSocket();
void failedOpenWebSocket(String message);
void hideError();
/*
void hideFormError();
void showFormError(Integer tokenError, Integer operateAsError);
*/
@StateStrategyType(SkipStrategy.class) | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/view/OpenWebSocketView.java
import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;
import org.erlymon.monitor.mvp.model.Event;
/*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.mvp.view;
/**
* Created by sergey on 17.03.17.
*/
@StateStrategyType(AddToEndSingleStrategy.class)
public interface OpenWebSocketView extends MvpView {
void startOpenWebSocket();
void finishOpenWebSocket();
void failedOpenWebSocket(String message);
void hideError();
/*
void hideFormError();
void showFormError(Integer tokenError, Integer operateAsError);
*/
@StateStrategyType(SkipStrategy.class) | void successOpenWebSocket(Event event); |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/view/GetDeviceView.java | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Device.java
// @StorIOSQLiteType(table = DevicesTable.TABLE)
// public class Device implements Parcelable {
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_ID, key = true)
// long id;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_NAME)
// @Since(3.0)
// @SerializedName("name")
// @Expose
// String name;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_UNIQUE_ID)
// @Since(3.0)
// @SerializedName("uniqueId")
// @Expose
// String uniqueId;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_STATUS)
// @Since(3.3)
// @SerializedName("status")
// @Expose
// String status;
//
// //@StorIOSQLiteColumn(name = DevicesTable.COLUMN_LAST_UPDATE)
// @Since(3.3)
// @SerializedName("lastUpdate")
// @Expose
// Date lastUpdate;
//
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_POSITION_ID)
// @Since(3.4)
// @SerializedName("positionId")
// @Expose
// Long positionId;
//
// public Device() {}
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getUniqueId() {
// return uniqueId;
// }
//
// public void setUniqueId(String uniqueId) {
// this.uniqueId = uniqueId;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// public Date getLastUpdate() {
// return lastUpdate;
// }
//
// public void setLastUpdate(Date lastUpdate) {
// this.lastUpdate = lastUpdate;
// }
//
// public Long getPositionId() {
// return positionId;
// }
//
// public void setPositionId(Long positionId) {
// this.positionId = positionId;
// }
//
// protected Device(Parcel in) {
// id = in.readLong();
// name = in.readString();
// uniqueId = in.readString();
// status = in.readString();
// long tmpLastUpdate = in.readLong();
// lastUpdate = tmpLastUpdate != -1 ? new Date(tmpLastUpdate) : null;
// positionId = in.readByte() == 0x00 ? null : in.readLong();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(id);
// dest.writeString(name);
// dest.writeString(uniqueId);
// dest.writeString(status);
// dest.writeLong(lastUpdate != null ? lastUpdate.getTime() : -1L);
// if (positionId == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(positionId);
// }
// }
//
// @SuppressWarnings("unused")
// public static final Creator<Device> CREATOR = new Creator<Device>() {
// @Override
// public Device createFromParcel(Parcel in) {
// return new Device(in);
// }
//
// @Override
// public Device[] newArray(int size) {
// return new Device[size];
// }
// };
//
// @Override
// public String toString() {
// return "Device{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", uniqueId='" + uniqueId + '\'' +
// ", status='" + status + '\'' +
// ", lastUpdate=" + lastUpdate +
// ", positionId=" + positionId +
// '}';
// }
// }
| import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;
import org.erlymon.monitor.mvp.model.Device; | /*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.mvp.view;
/**
* Created by sergey on 17.03.17.
*/
@StateStrategyType(AddToEndSingleStrategy.class)
public interface GetDeviceView extends MvpView {
void startGetDevice();
void finishGetDevice();
void failedGetDevice(String message);
void hideError();
/*
void hideFormError();
void showFormError(Integer tokenError, Integer operateAsError);
*/
@StateStrategyType(SkipStrategy.class) | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Device.java
// @StorIOSQLiteType(table = DevicesTable.TABLE)
// public class Device implements Parcelable {
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_ID, key = true)
// long id;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_NAME)
// @Since(3.0)
// @SerializedName("name")
// @Expose
// String name;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_UNIQUE_ID)
// @Since(3.0)
// @SerializedName("uniqueId")
// @Expose
// String uniqueId;
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_STATUS)
// @Since(3.3)
// @SerializedName("status")
// @Expose
// String status;
//
// //@StorIOSQLiteColumn(name = DevicesTable.COLUMN_LAST_UPDATE)
// @Since(3.3)
// @SerializedName("lastUpdate")
// @Expose
// Date lastUpdate;
//
//
// @StorIOSQLiteColumn(name = DevicesTable.COLUMN_POSITION_ID)
// @Since(3.4)
// @SerializedName("positionId")
// @Expose
// Long positionId;
//
// public Device() {}
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getUniqueId() {
// return uniqueId;
// }
//
// public void setUniqueId(String uniqueId) {
// this.uniqueId = uniqueId;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// public Date getLastUpdate() {
// return lastUpdate;
// }
//
// public void setLastUpdate(Date lastUpdate) {
// this.lastUpdate = lastUpdate;
// }
//
// public Long getPositionId() {
// return positionId;
// }
//
// public void setPositionId(Long positionId) {
// this.positionId = positionId;
// }
//
// protected Device(Parcel in) {
// id = in.readLong();
// name = in.readString();
// uniqueId = in.readString();
// status = in.readString();
// long tmpLastUpdate = in.readLong();
// lastUpdate = tmpLastUpdate != -1 ? new Date(tmpLastUpdate) : null;
// positionId = in.readByte() == 0x00 ? null : in.readLong();
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(id);
// dest.writeString(name);
// dest.writeString(uniqueId);
// dest.writeString(status);
// dest.writeLong(lastUpdate != null ? lastUpdate.getTime() : -1L);
// if (positionId == null) {
// dest.writeByte((byte) (0x00));
// } else {
// dest.writeByte((byte) (0x01));
// dest.writeLong(positionId);
// }
// }
//
// @SuppressWarnings("unused")
// public static final Creator<Device> CREATOR = new Creator<Device>() {
// @Override
// public Device createFromParcel(Parcel in) {
// return new Device(in);
// }
//
// @Override
// public Device[] newArray(int size) {
// return new Device[size];
// }
// };
//
// @Override
// public String toString() {
// return "Device{" +
// "id=" + id +
// ", name='" + name + '\'' +
// ", uniqueId='" + uniqueId + '\'' +
// ", status='" + status + '\'' +
// ", lastUpdate=" + lastUpdate +
// ", positionId=" + positionId +
// '}';
// }
// }
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/view/GetDeviceView.java
import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy;
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;
import org.erlymon.monitor.mvp.model.Device;
/*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.mvp.view;
/**
* Created by sergey on 17.03.17.
*/
@StateStrategyType(AddToEndSingleStrategy.class)
public interface GetDeviceView extends MvpView {
void startGetDevice();
void finishGetDevice();
void failedGetDevice(String message);
void hideError();
/*
void hideFormError();
void showFormError(Integer tokenError, Integer operateAsError);
*/
@StateStrategyType(SkipStrategy.class) | void successGetDevice(Device device); |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/RestApiModule.java | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/api/RestApi.java
// public interface RestApi {
// @GET("server")
// Observable<Server> getServer();
//
// @PUT("server")
// Observable<Server> updateServer(@Body Server server);
//
// //http://web.erlymon.org/api/session
// @GET("session")
// Observable<User> getSession();
//
// @FormUrlEncoded
// @POST("session")
// Observable<User> createSession(@Field("email") String email, @Field("password") String password);
//
// //@Headers("Content-Type: application/json")
// @DELETE("session")
// Observable<Void> deleteSession();
//
// /**
// * Unrecognized field "twelveHourFormat" (class org.traccar.model.User), not marked as ignorable (13 known properties: "readonly", "name", "speedUnit", "latitude", "admin", "longitude", "zoom", "language", "distanceUnit", "id", "password", "email", "map"])
// */
// @POST("users")
// Observable<User> createUser(@Body User user);
//
// /**
// * {"details":"Column \"LANGUAGE\" not found; SQL statement:\nUPDATE users SET\n name = ?,\n email = ?,\n admin = ?,\n map = ?,\n language = ?,\n distanceUnit = ?,\n speedUnit = ?,\n latitude = ?,\n longitude = ?,\n zoom = ?\n WHERE id = ?; [42122-191] - JdbcSQLException (... < QueryBuilder:61 < *:131 < DataManager:201 < UserResource:66 < ...)","message":"Column \"LANGUAGE\" not found; SQL statement:\nUPDATE users SET\n name = ?,\n email = ?,\n admin = ?,\n map = ?,\n language = ?,\n distanceUnit = ?,\n speedUnit = ?,\n latitude = ?,\n longitude = ?,\n zoom = ?\n WHERE id = ?; [42122-191]"}
// */
// @PUT("users/{id}")
// Observable<User> updateUser(@Path("id") long id, @Body User user);
//
// @GET("users")
// Observable<List<User>> getUsers();
//
// @Headers("Content-Type: application/json")
// @DELETE("users/{id}")
// Observable<Void> deleteUser(@Path("id") long id);
//
// @POST("devices")
// Observable<Device> createDevice(@Body Device device);
//
// @PUT("devices/{id}")
// Observable<Device> updateDevice(@Path("id") long id, @Body Device device);
//
// //http://web.erlymon.org/api/devices/10246?_dc=1452209536829
// //http://web.erlymon.org/api/devices/10246
// @Headers("Content-Type: application/json")
// @DELETE("devices/{id}")
// Observable<Void> deleteDevice(@Path("id") long id);
//
// @GET("devices")
// Observable<List<Device>> getDevices();
//
// @GET("devices")
// Observable<List<Device>> getDevices(@Query("all") boolean all);
//
// @GET("devices")
// Observable<List<Device>> getDevices(@Query("userId") long userId);
//
// // http://web.erlymon.org/api/positions?_dc=1452345778504&deviceId=10290&from=2016-01-06T21%3A00%3A00.000Z&to=2016-01-09T20%3A45%3A00.000Z&page=1&start=0&limit=25
// @GET("positions")
// Observable<List<Position>> getPositions(@Query("deviceId") long deviceId, @Query("from") QueryDate from, @Query("to") QueryDate to);
//
// // {"deviceId":10995,"type":"engineResume","id":-1}
// // {"deviceId":10995,"type":"positionPeriodic","id":-1,"attributes":{"frequency":1}}
// @POST("commands")
// Observable<Void> createCommand(@Body Command command);
//
// @POST("permissions")
// Observable<Void> createPermission(@Body Permission permission);
//
// //@DELETE("permissions")
// @HTTP(method = "DELETE", path = "permissions", hasBody = true)
// Observable<Void> deletePermission(@Body Permission permission);
// }
| import org.erlymon.monitor.api.RestApi;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit; | /*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {RetrofitModule.class})
public class RestApiModule {
@Provides
@Singleton | // Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/api/RestApi.java
// public interface RestApi {
// @GET("server")
// Observable<Server> getServer();
//
// @PUT("server")
// Observable<Server> updateServer(@Body Server server);
//
// //http://web.erlymon.org/api/session
// @GET("session")
// Observable<User> getSession();
//
// @FormUrlEncoded
// @POST("session")
// Observable<User> createSession(@Field("email") String email, @Field("password") String password);
//
// //@Headers("Content-Type: application/json")
// @DELETE("session")
// Observable<Void> deleteSession();
//
// /**
// * Unrecognized field "twelveHourFormat" (class org.traccar.model.User), not marked as ignorable (13 known properties: "readonly", "name", "speedUnit", "latitude", "admin", "longitude", "zoom", "language", "distanceUnit", "id", "password", "email", "map"])
// */
// @POST("users")
// Observable<User> createUser(@Body User user);
//
// /**
// * {"details":"Column \"LANGUAGE\" not found; SQL statement:\nUPDATE users SET\n name = ?,\n email = ?,\n admin = ?,\n map = ?,\n language = ?,\n distanceUnit = ?,\n speedUnit = ?,\n latitude = ?,\n longitude = ?,\n zoom = ?\n WHERE id = ?; [42122-191] - JdbcSQLException (... < QueryBuilder:61 < *:131 < DataManager:201 < UserResource:66 < ...)","message":"Column \"LANGUAGE\" not found; SQL statement:\nUPDATE users SET\n name = ?,\n email = ?,\n admin = ?,\n map = ?,\n language = ?,\n distanceUnit = ?,\n speedUnit = ?,\n latitude = ?,\n longitude = ?,\n zoom = ?\n WHERE id = ?; [42122-191]"}
// */
// @PUT("users/{id}")
// Observable<User> updateUser(@Path("id") long id, @Body User user);
//
// @GET("users")
// Observable<List<User>> getUsers();
//
// @Headers("Content-Type: application/json")
// @DELETE("users/{id}")
// Observable<Void> deleteUser(@Path("id") long id);
//
// @POST("devices")
// Observable<Device> createDevice(@Body Device device);
//
// @PUT("devices/{id}")
// Observable<Device> updateDevice(@Path("id") long id, @Body Device device);
//
// //http://web.erlymon.org/api/devices/10246?_dc=1452209536829
// //http://web.erlymon.org/api/devices/10246
// @Headers("Content-Type: application/json")
// @DELETE("devices/{id}")
// Observable<Void> deleteDevice(@Path("id") long id);
//
// @GET("devices")
// Observable<List<Device>> getDevices();
//
// @GET("devices")
// Observable<List<Device>> getDevices(@Query("all") boolean all);
//
// @GET("devices")
// Observable<List<Device>> getDevices(@Query("userId") long userId);
//
// // http://web.erlymon.org/api/positions?_dc=1452345778504&deviceId=10290&from=2016-01-06T21%3A00%3A00.000Z&to=2016-01-09T20%3A45%3A00.000Z&page=1&start=0&limit=25
// @GET("positions")
// Observable<List<Position>> getPositions(@Query("deviceId") long deviceId, @Query("from") QueryDate from, @Query("to") QueryDate to);
//
// // {"deviceId":10995,"type":"engineResume","id":-1}
// // {"deviceId":10995,"type":"positionPeriodic","id":-1,"attributes":{"frequency":1}}
// @POST("commands")
// Observable<Void> createCommand(@Body Command command);
//
// @POST("permissions")
// Observable<Void> createPermission(@Body Permission permission);
//
// //@DELETE("permissions")
// @HTTP(method = "DELETE", path = "permissions", hasBody = true)
// Observable<Void> deletePermission(@Body Permission permission);
// }
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/RestApiModule.java
import org.erlymon.monitor.api.RestApi;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
/*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {RetrofitModule.class})
public class RestApiModule {
@Provides
@Singleton | public RestApi provideRestApi(Retrofit retrofit) { |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/WebSocketModule.java | // Path: erlymon-monitor-app/src/main/java/com/appunite/websocket/rx/object/GsonObjectSerializer.java
// public class GsonObjectSerializer implements ObjectSerializer {
//
// @Nonnull
// private final Gson gson;
// @Nonnull
// private final Type typeOfT;
//
// public GsonObjectSerializer(@Nonnull Gson gson, @Nonnull Type typeOfT) {
// this.gson = gson;
// this.typeOfT = typeOfT;
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull String message) throws ObjectParseException {
// try {
// return gson.fromJson(message, typeOfT);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull byte[] message) throws ObjectParseException {
// throw new ObjectParseException("Could not parse binary messages");
// }
//
// @Nonnull
// @Override
// public byte[] deserializeBinary(@Nonnull Object message) throws ObjectParseException {
// throw new IllegalStateException("Only serialization to string is available");
// }
//
// @Nonnull
// @Override
// public String deserializeString(@Nonnull Object message) throws ObjectParseException {
// try {
// return gson.toJson(message);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Override
// public boolean isBinary(@Nonnull Object message) {
// return false;
// }
// }
//
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
| import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import android.content.SharedPreferences;
import com.appunite.websocket.rx.RxWebSockets;
import com.appunite.websocket.rx.object.GsonObjectSerializer;
import com.appunite.websocket.rx.object.ObjectSerializer;
import com.appunite.websocket.rx.object.RxObjectWebSockets;
import com.google.gson.Gson;
import org.erlymon.monitor.mvp.model.Event;
import javax.inject.Singleton; | /*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {HttpClientModule.class, GsonModule.class})
public class WebSocketModule {
@Provides
@Singleton
public RxObjectWebSockets provideRxObjectWebSockets(RxWebSockets rxWebSockets, ObjectSerializer serializer) {
return new RxObjectWebSockets(rxWebSockets, serializer);
}
@Provides
@Singleton
public RxWebSockets provideRxWebSockets(OkHttpClient client, SharedPreferences sharedPreferences) {
boolean sslOrTls = sharedPreferences.getBoolean("sslOrTls", false);
String dns = sharedPreferences.getString("dns", "web.erlymon.org");
return new RxWebSockets(client, new Request.Builder()
.get()
.url("{socket}://{dns}/api/socket".replace("{socket}", sslOrTls? "wss" : "ws").replace("{dns}", dns))
//.url("{socket}://{dns}/api/socket".replace("{socket}", mSslOrTls ? "wss" : "ws").replace("{dns}", mDns))
.addHeader("Sec-WebSocket-Protocol", "chat")
.build());
}
@Provides
@Singleton
public ObjectSerializer provideObjectSerializer(Gson gson) { | // Path: erlymon-monitor-app/src/main/java/com/appunite/websocket/rx/object/GsonObjectSerializer.java
// public class GsonObjectSerializer implements ObjectSerializer {
//
// @Nonnull
// private final Gson gson;
// @Nonnull
// private final Type typeOfT;
//
// public GsonObjectSerializer(@Nonnull Gson gson, @Nonnull Type typeOfT) {
// this.gson = gson;
// this.typeOfT = typeOfT;
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull String message) throws ObjectParseException {
// try {
// return gson.fromJson(message, typeOfT);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull byte[] message) throws ObjectParseException {
// throw new ObjectParseException("Could not parse binary messages");
// }
//
// @Nonnull
// @Override
// public byte[] deserializeBinary(@Nonnull Object message) throws ObjectParseException {
// throw new IllegalStateException("Only serialization to string is available");
// }
//
// @Nonnull
// @Override
// public String deserializeString(@Nonnull Object message) throws ObjectParseException {
// try {
// return gson.toJson(message);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Override
// public boolean isBinary(@Nonnull Object message) {
// return false;
// }
// }
//
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/WebSocketModule.java
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import android.content.SharedPreferences;
import com.appunite.websocket.rx.RxWebSockets;
import com.appunite.websocket.rx.object.GsonObjectSerializer;
import com.appunite.websocket.rx.object.ObjectSerializer;
import com.appunite.websocket.rx.object.RxObjectWebSockets;
import com.google.gson.Gson;
import org.erlymon.monitor.mvp.model.Event;
import javax.inject.Singleton;
/*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {HttpClientModule.class, GsonModule.class})
public class WebSocketModule {
@Provides
@Singleton
public RxObjectWebSockets provideRxObjectWebSockets(RxWebSockets rxWebSockets, ObjectSerializer serializer) {
return new RxObjectWebSockets(rxWebSockets, serializer);
}
@Provides
@Singleton
public RxWebSockets provideRxWebSockets(OkHttpClient client, SharedPreferences sharedPreferences) {
boolean sslOrTls = sharedPreferences.getBoolean("sslOrTls", false);
String dns = sharedPreferences.getString("dns", "web.erlymon.org");
return new RxWebSockets(client, new Request.Builder()
.get()
.url("{socket}://{dns}/api/socket".replace("{socket}", sslOrTls? "wss" : "ws").replace("{dns}", dns))
//.url("{socket}://{dns}/api/socket".replace("{socket}", mSslOrTls ? "wss" : "ws").replace("{dns}", mDns))
.addHeader("Sec-WebSocket-Protocol", "chat")
.build());
}
@Provides
@Singleton
public ObjectSerializer provideObjectSerializer(Gson gson) { | return new GsonObjectSerializer(gson, Event.class); |
erlymon/erlymon-monitor-android | erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/WebSocketModule.java | // Path: erlymon-monitor-app/src/main/java/com/appunite/websocket/rx/object/GsonObjectSerializer.java
// public class GsonObjectSerializer implements ObjectSerializer {
//
// @Nonnull
// private final Gson gson;
// @Nonnull
// private final Type typeOfT;
//
// public GsonObjectSerializer(@Nonnull Gson gson, @Nonnull Type typeOfT) {
// this.gson = gson;
// this.typeOfT = typeOfT;
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull String message) throws ObjectParseException {
// try {
// return gson.fromJson(message, typeOfT);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull byte[] message) throws ObjectParseException {
// throw new ObjectParseException("Could not parse binary messages");
// }
//
// @Nonnull
// @Override
// public byte[] deserializeBinary(@Nonnull Object message) throws ObjectParseException {
// throw new IllegalStateException("Only serialization to string is available");
// }
//
// @Nonnull
// @Override
// public String deserializeString(@Nonnull Object message) throws ObjectParseException {
// try {
// return gson.toJson(message);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Override
// public boolean isBinary(@Nonnull Object message) {
// return false;
// }
// }
//
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
| import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import android.content.SharedPreferences;
import com.appunite.websocket.rx.RxWebSockets;
import com.appunite.websocket.rx.object.GsonObjectSerializer;
import com.appunite.websocket.rx.object.ObjectSerializer;
import com.appunite.websocket.rx.object.RxObjectWebSockets;
import com.google.gson.Gson;
import org.erlymon.monitor.mvp.model.Event;
import javax.inject.Singleton; | /*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {HttpClientModule.class, GsonModule.class})
public class WebSocketModule {
@Provides
@Singleton
public RxObjectWebSockets provideRxObjectWebSockets(RxWebSockets rxWebSockets, ObjectSerializer serializer) {
return new RxObjectWebSockets(rxWebSockets, serializer);
}
@Provides
@Singleton
public RxWebSockets provideRxWebSockets(OkHttpClient client, SharedPreferences sharedPreferences) {
boolean sslOrTls = sharedPreferences.getBoolean("sslOrTls", false);
String dns = sharedPreferences.getString("dns", "web.erlymon.org");
return new RxWebSockets(client, new Request.Builder()
.get()
.url("{socket}://{dns}/api/socket".replace("{socket}", sslOrTls? "wss" : "ws").replace("{dns}", dns))
//.url("{socket}://{dns}/api/socket".replace("{socket}", mSslOrTls ? "wss" : "ws").replace("{dns}", mDns))
.addHeader("Sec-WebSocket-Protocol", "chat")
.build());
}
@Provides
@Singleton
public ObjectSerializer provideObjectSerializer(Gson gson) { | // Path: erlymon-monitor-app/src/main/java/com/appunite/websocket/rx/object/GsonObjectSerializer.java
// public class GsonObjectSerializer implements ObjectSerializer {
//
// @Nonnull
// private final Gson gson;
// @Nonnull
// private final Type typeOfT;
//
// public GsonObjectSerializer(@Nonnull Gson gson, @Nonnull Type typeOfT) {
// this.gson = gson;
// this.typeOfT = typeOfT;
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull String message) throws ObjectParseException {
// try {
// return gson.fromJson(message, typeOfT);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Nonnull
// @Override
// public Object serialize(@Nonnull byte[] message) throws ObjectParseException {
// throw new ObjectParseException("Could not parse binary messages");
// }
//
// @Nonnull
// @Override
// public byte[] deserializeBinary(@Nonnull Object message) throws ObjectParseException {
// throw new IllegalStateException("Only serialization to string is available");
// }
//
// @Nonnull
// @Override
// public String deserializeString(@Nonnull Object message) throws ObjectParseException {
// try {
// return gson.toJson(message);
// } catch (JsonParseException e) {
// throw new ObjectParseException("Could not parse", e);
// }
// }
//
// @Override
// public boolean isBinary(@Nonnull Object message) {
// return false;
// }
// }
//
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/mvp/model/Event.java
// public class Event {
// private List<Device> devices;
// private List<Position> positions;
//
// public Event() {}
//
// public Event(List<Device> devices, List<Position> positions) {
// this.devices = devices;
// this.positions = positions;
// }
// public List<Device> getDevices() {
// return devices;
// }
//
// public List<Position> getPositions() {
// return positions;
// }
//
// @Override
// public String toString() {
// return "Event{" +
// "devices=" + devices +
// ", positions=" + positions +
// '}';
// }
// }
// Path: erlymon-monitor-app/src/main/java/org/erlymon/monitor/dagger/module/WebSocketModule.java
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import android.content.SharedPreferences;
import com.appunite.websocket.rx.RxWebSockets;
import com.appunite.websocket.rx.object.GsonObjectSerializer;
import com.appunite.websocket.rx.object.ObjectSerializer;
import com.appunite.websocket.rx.object.RxObjectWebSockets;
import com.google.gson.Gson;
import org.erlymon.monitor.mvp.model.Event;
import javax.inject.Singleton;
/*
* Copyright (c) 2016, Sergey Penkovsky <sergey.penkovsky@gmail.com>
*
* This file is part of Erlymon Monitor.
*
* Erlymon Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Erlymon Monitor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Erlymon Monitor. If not, see <http://www.gnu.org/licenses/>.
*/
package org.erlymon.monitor.dagger.module;
/**
* Created by sergey on 17.03.17.
*/
@Module(includes = {HttpClientModule.class, GsonModule.class})
public class WebSocketModule {
@Provides
@Singleton
public RxObjectWebSockets provideRxObjectWebSockets(RxWebSockets rxWebSockets, ObjectSerializer serializer) {
return new RxObjectWebSockets(rxWebSockets, serializer);
}
@Provides
@Singleton
public RxWebSockets provideRxWebSockets(OkHttpClient client, SharedPreferences sharedPreferences) {
boolean sslOrTls = sharedPreferences.getBoolean("sslOrTls", false);
String dns = sharedPreferences.getString("dns", "web.erlymon.org");
return new RxWebSockets(client, new Request.Builder()
.get()
.url("{socket}://{dns}/api/socket".replace("{socket}", sslOrTls? "wss" : "ws").replace("{dns}", dns))
//.url("{socket}://{dns}/api/socket".replace("{socket}", mSslOrTls ? "wss" : "ws").replace("{dns}", mDns))
.addHeader("Sec-WebSocket-Protocol", "chat")
.build());
}
@Provides
@Singleton
public ObjectSerializer provideObjectSerializer(Gson gson) { | return new GsonObjectSerializer(gson, Event.class); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaImputationTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.imputations.*;
import com.thoughtworks.datacommons.prepbuddy.rdds.TransformableRDD;
import com.thoughtworks.datacommons.prepbuddy.utils.RowRecord;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaImputationTest extends JavaSparkTestCase {
@Test
public void shouldImputeTheValueWithTheMean() {
JavaRDD<String> initialDataSet = javaSparkContext.parallelize(Arrays.asList(
"07434677419,07371326239,Incoming,31,Wed Sep 15 19:17:44 +0100 2010",
"07641036117,01666472054,Outgoing,20,Mon Feb 11 07:18:23 +0000 1980",
"07641036117,07371326239,Incoming, ,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07681546436,Missed,12,Mon Feb 11 08:04:42 +0000 1980"
)); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaImputationTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.imputations.*;
import com.thoughtworks.datacommons.prepbuddy.rdds.TransformableRDD;
import com.thoughtworks.datacommons.prepbuddy.utils.RowRecord;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaImputationTest extends JavaSparkTestCase {
@Test
public void shouldImputeTheValueWithTheMean() {
JavaRDD<String> initialDataSet = javaSparkContext.parallelize(Arrays.asList(
"07434677419,07371326239,Incoming,31,Wed Sep 15 19:17:44 +0100 2010",
"07641036117,01666472054,Outgoing,20,Mon Feb 11 07:18:23 +0000 1980",
"07641036117,07371326239,Incoming, ,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07681546436,Missed,12,Mon Feb 11 08:04:42 +0000 1980"
)); | JavaTransformableRDD initialRDD = new JavaTransformableRDD(initialDataSet, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaClusterTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.LevenshteinDistance;
import com.thoughtworks.datacommons.prepbuddy.clusterers.NGramFingerprintAlgorithm;
import com.thoughtworks.datacommons.prepbuddy.clusterers.SimpleFingerprintAlgorithm;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import scala.Tuple2;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaClusterTest extends JavaSparkTestCase {
@Test
public void shouldGiveClusterOfSimilarColumnValues() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList("CLUSTER Of Finger print", "finger print of cluster", "finger print for cluster")); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaClusterTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.LevenshteinDistance;
import com.thoughtworks.datacommons.prepbuddy.clusterers.NGramFingerprintAlgorithm;
import com.thoughtworks.datacommons.prepbuddy.clusterers.SimpleFingerprintAlgorithm;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import scala.Tuple2;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaClusterTest extends JavaSparkTestCase {
@Test
public void shouldGiveClusterOfSimilarColumnValues() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList("CLUSTER Of Finger print", "finger print of cluster", "finger print for cluster")); | JavaTransformableRDD initialRDD = new JavaTransformableRDD(initialDataset, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaFacetTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.TextFacets;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import scala.Tuple2;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaFacetTest extends JavaSparkTestCase {
@Test
public void _TextFacetShouldGiveCountOfPair() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList("X,Y", "A,B", "X,Z", "A,Q", "A,E")); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaFacetTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.TextFacets;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import scala.Tuple2;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaFacetTest extends JavaSparkTestCase {
@Test
public void _TextFacetShouldGiveCountOfPair() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList("X,Y", "A,B", "X,Z", "A,Q", "A,E")); | JavaTransformableRDD initialRDD = new JavaTransformableRDD(initialDataset, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaMergeSplitTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaMergeSplitTest extends JavaSparkTestCase {
@Test
public void shouldMergeGivenColumnsWithTheSeparator() {
List<String> data = Arrays.asList(
"John,Male,21,Canada",
"Smith, Male, 30, UK",
"Larry, Male, 23, USA",
"Fiona, Female,18,USA"
);
JavaRDD<String> dataset = javaSparkContext.parallelize(data); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaMergeSplitTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaMergeSplitTest extends JavaSparkTestCase {
@Test
public void shouldMergeGivenColumnsWithTheSeparator() {
List<String> data = Arrays.asList(
"John,Male,21,Canada",
"Smith, Male, 30, UK",
"Larry, Male, 23, USA",
"Fiona, Female,18,USA"
);
JavaRDD<String> dataset = javaSparkContext.parallelize(data); | JavaTransformableRDD transformableRDD = new JavaTransformableRDD(dataset, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaSmoothingTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.smoothers.SimpleMovingAverageMethod;
import com.thoughtworks.datacommons.prepbuddy.smoothers.WeightedMovingAverageMethod;
import com.thoughtworks.datacommons.prepbuddy.smoothers.Weights;
import org.apache.spark.api.java.JavaDoubleRDD;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaSmoothingTest extends JavaSparkTestCase {
@Test
public void shouldSmoothDataSetBySimpleMovingAverage() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList(
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"
), 3); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaSmoothingTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.smoothers.SimpleMovingAverageMethod;
import com.thoughtworks.datacommons.prepbuddy.smoothers.WeightedMovingAverageMethod;
import com.thoughtworks.datacommons.prepbuddy.smoothers.Weights;
import org.apache.spark.api.java.JavaDoubleRDD;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaSmoothingTest extends JavaSparkTestCase {
@Test
public void shouldSmoothDataSetBySimpleMovingAverage() {
JavaRDD<String> initialDataset = javaSparkContext.parallelize(Arrays.asList(
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"
), 3); | JavaTransformableRDD transformableRDD = new JavaTransformableRDD(initialDataset, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaTransformableRDDTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.SimpleFingerprintAlgorithm;
import com.thoughtworks.datacommons.prepbuddy.utils.PivotTable;
import com.thoughtworks.datacommons.prepbuddy.utils.RowRecord;
import org.apache.spark.api.java.JavaDoubleRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaTransformableRDDTest extends JavaSparkTestCase {
@Test
public void shouldBeAbleToDeduplicate() {
JavaRDD<String> numbers = javaSparkContext.parallelize(Arrays.asList(
"One,Two,Three",
"One,Two,Three",
"One,Two,Three",
"Ten,Eleven,Twelve"
)); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaTransformableRDDTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.clusterers.SimpleFingerprintAlgorithm;
import com.thoughtworks.datacommons.prepbuddy.utils.PivotTable;
import com.thoughtworks.datacommons.prepbuddy.utils.RowRecord;
import org.apache.spark.api.java.JavaDoubleRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaTransformableRDDTest extends JavaSparkTestCase {
@Test
public void shouldBeAbleToDeduplicate() {
JavaRDD<String> numbers = javaSparkContext.parallelize(Arrays.asList(
"One,Two,Three",
"One,Two,Three",
"One,Two,Three",
"Ten,Eleven,Twelve"
)); | JavaTransformableRDD javaTransformableRDD = new JavaTransformableRDD(numbers, FileType.CSV); |
data-commons/prep-buddy | src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaNormalizersTest.java | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
| import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.normalizers.DecimalScalingNormalizer;
import com.thoughtworks.datacommons.prepbuddy.normalizers.MinMaxNormalizer;
import com.thoughtworks.datacommons.prepbuddy.normalizers.ZScoreNormalizer;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals; | package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaNormalizersTest extends JavaSparkTestCase {
@Test
public void shouldNormalizeRecordsUsingMinMaxNormalizer() throws Exception {
JavaRDD<String> initialDataSet = javaSparkContext.parallelize(Arrays.asList(
"07434677419,07371326239,Incoming,211,Wed Sep 15 19:17:44 +0100 2010",
"07641036117,01666472054,Outgoing,0,Mon Feb 11 07:18:23 +0000 1980",
"07641036117,07371326239,Incoming,45,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07371326239,Incoming,45,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07681546436,Missed,12,Mon Feb 11 08:04:42 +0000 1980"
)); | // Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/JavaSparkTestCase.java
// public class JavaSparkTestCase implements Serializable {
// protected transient JavaSparkContext javaSparkContext;
//
// @Before
// public void setUp() throws Exception {
// SparkConf sparkConf = new SparkConf().setAppName(getClass().getName()).setMaster("local");
// Logger.getLogger("org").setLevel(Level.OFF);
// Logger.getLogger("akka").setLevel(Level.OFF);
// javaSparkContext = new JavaSparkContext(sparkConf);
// }
//
// @After
// public void tearDown() throws Exception {
// javaSparkContext.close();
// }
// }
//
// Path: src/main/scala/com/thoughtworks/datacommons/prepbuddy/api/java/types/FileType.java
// public class FileType {
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType CSV = CSV$.MODULE$;
// public static final com.thoughtworks.datacommons.prepbuddy.types.FileType TSV = TSV$.MODULE$;
// }
// Path: src/test/java/com/thoughtworks/datacommons/prepbuddy/api/java/JavaNormalizersTest.java
import com.thoughtworks.datacommons.prepbuddy.api.JavaSparkTestCase;
import com.thoughtworks.datacommons.prepbuddy.api.java.types.FileType;
import com.thoughtworks.datacommons.prepbuddy.normalizers.DecimalScalingNormalizer;
import com.thoughtworks.datacommons.prepbuddy.normalizers.MinMaxNormalizer;
import com.thoughtworks.datacommons.prepbuddy.normalizers.ZScoreNormalizer;
import org.apache.spark.api.java.JavaRDD;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
package com.thoughtworks.datacommons.prepbuddy.api.java;
public class JavaNormalizersTest extends JavaSparkTestCase {
@Test
public void shouldNormalizeRecordsUsingMinMaxNormalizer() throws Exception {
JavaRDD<String> initialDataSet = javaSparkContext.parallelize(Arrays.asList(
"07434677419,07371326239,Incoming,211,Wed Sep 15 19:17:44 +0100 2010",
"07641036117,01666472054,Outgoing,0,Mon Feb 11 07:18:23 +0000 1980",
"07641036117,07371326239,Incoming,45,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07371326239,Incoming,45,Mon Feb 11 07:45:42 +0000 1980",
"07641036117,07681546436,Missed,12,Mon Feb 11 08:04:42 +0000 1980"
)); | JavaTransformableRDD initialRDD = new JavaTransformableRDD(initialDataSet, FileType.CSV); |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/api/Expression.java | // Path: src/main/java/gov/nasa/jpf/constraints/types/Type.java
// public interface Type<T> {
//
// public String getName();
//
// public String[] getOtherNames();
//
// public Class<T> getCanonicalClass();
//
// public Class<?>[] getOtherClasses();
//
// public T cast(Object other);
//
// public T getDefaultValue();
//
// public Type<?> getSuperType();
//
// public <O> CastOperation<? super O,? extends T> cast(Type<O> fromType);
// public <O> CastOperation<? super O,? extends T> requireCast(Type<O> fromType);
//
// public abstract T parse(String string);
//
//
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/util/AbstractPrintable.java
// public abstract class AbstractPrintable implements Printable {
//
// @Override
// public String toString() {
// try {
// StringBuilder sb = new StringBuilder();
// print(sb);
// return sb.toString();
// }
// catch(IOException ex) {
// throw new IllegalStateException("Unexpected IOException while writing to StringBuilder", ex);
// }
// }
// }
| import gov.nasa.jpf.constraints.types.Type;
import gov.nasa.jpf.constraints.util.AbstractPrintable;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.api;
/**
* Expressions consist of terms, and can be evaluated E
*/
public abstract class Expression<E> extends AbstractPrintable {
public static final int QUOTE_IDENTIFIERS = 1;
public static final int INCLUDE_VARIABLE_TYPE = 2;
public static final int INCLUDE_BOUND_DECL_TYPE = 4;
public static final int SIMPLE_PROP_OPERATORS = 8;
public static final int DEFAULT_FLAGS = QUOTE_IDENTIFIERS | INCLUDE_BOUND_DECL_TYPE;
public static final int JAVA_COMPAT_FLAGS = SIMPLE_PROP_OPERATORS;
public static boolean quoteIdentifiers(int printFlags) {
return (printFlags & QUOTE_IDENTIFIERS) == QUOTE_IDENTIFIERS;
}
public static boolean includeVariableType(int printFlags) {
return (printFlags & INCLUDE_VARIABLE_TYPE) == INCLUDE_VARIABLE_TYPE;
}
public static boolean includeBoundDeclType(int printFlags) {
return (printFlags & INCLUDE_BOUND_DECL_TYPE) == INCLUDE_BOUND_DECL_TYPE;
}
public static Expression<?>[] NO_CHILDREN = new Expression[0];
/**
* evaluates using the provided values for symbolic variables
*
* @param values
* @return
*/
public abstract E evaluate(Valuation values);
/**
* collect all symbolic variables
*
* @param names
*/
public abstract void collectFreeVariables(Collection<? super Variable<?>> variables);
public abstract <R,D> R accept(ExpressionVisitor<R, D> visitor, D data);
| // Path: src/main/java/gov/nasa/jpf/constraints/types/Type.java
// public interface Type<T> {
//
// public String getName();
//
// public String[] getOtherNames();
//
// public Class<T> getCanonicalClass();
//
// public Class<?>[] getOtherClasses();
//
// public T cast(Object other);
//
// public T getDefaultValue();
//
// public Type<?> getSuperType();
//
// public <O> CastOperation<? super O,? extends T> cast(Type<O> fromType);
// public <O> CastOperation<? super O,? extends T> requireCast(Type<O> fromType);
//
// public abstract T parse(String string);
//
//
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/util/AbstractPrintable.java
// public abstract class AbstractPrintable implements Printable {
//
// @Override
// public String toString() {
// try {
// StringBuilder sb = new StringBuilder();
// print(sb);
// return sb.toString();
// }
// catch(IOException ex) {
// throw new IllegalStateException("Unexpected IOException while writing to StringBuilder", ex);
// }
// }
// }
// Path: src/main/java/gov/nasa/jpf/constraints/api/Expression.java
import gov.nasa.jpf.constraints.types.Type;
import gov.nasa.jpf.constraints.util.AbstractPrintable;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.api;
/**
* Expressions consist of terms, and can be evaluated E
*/
public abstract class Expression<E> extends AbstractPrintable {
public static final int QUOTE_IDENTIFIERS = 1;
public static final int INCLUDE_VARIABLE_TYPE = 2;
public static final int INCLUDE_BOUND_DECL_TYPE = 4;
public static final int SIMPLE_PROP_OPERATORS = 8;
public static final int DEFAULT_FLAGS = QUOTE_IDENTIFIERS | INCLUDE_BOUND_DECL_TYPE;
public static final int JAVA_COMPAT_FLAGS = SIMPLE_PROP_OPERATORS;
public static boolean quoteIdentifiers(int printFlags) {
return (printFlags & QUOTE_IDENTIFIERS) == QUOTE_IDENTIFIERS;
}
public static boolean includeVariableType(int printFlags) {
return (printFlags & INCLUDE_VARIABLE_TYPE) == INCLUDE_VARIABLE_TYPE;
}
public static boolean includeBoundDeclType(int printFlags) {
return (printFlags & INCLUDE_BOUND_DECL_TYPE) == INCLUDE_BOUND_DECL_TYPE;
}
public static Expression<?>[] NO_CHILDREN = new Expression[0];
/**
* evaluates using the provided values for symbolic variables
*
* @param values
* @return
*/
public abstract E evaluate(Valuation values);
/**
* collect all symbolic variables
*
* @param names
*/
public abstract void collectFreeVariables(Collection<? super Variable<?>> variables);
public abstract <R,D> R accept(ExpressionVisitor<R, D> visitor, D data);
| public abstract Type<E> getType(); |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/api/ValuationEntry.java | // Path: src/main/java/gov/nasa/jpf/constraints/expressions/Constant.java
// public class Constant<E> extends AbstractExpression<E> {
//
// public static <E> Constant<E> create(Type<E> type, E value) {
// return new Constant<E>(type, value);
// }
//
// public static <E> Constant<E> createParsed(Type<E> type, String txt) {
// return new Constant<E>(type, type.parse(txt));
// }
//
// public static <E> Constant<E> createCasted(Type<E> type, Object value) {
// return new Constant<E>(type, type.cast(value));
// }
//
// private final Type<E> type;
// private final E value;
//
// public Constant(Type<E> type, E value) {
// this.type = type;
// this.value = value;
// }
//
//
// @Override
// public E evaluate(Valuation values) {
// return this.value;
// }
//
//
// @Override
// public void collectFreeVariables(Collection<? super Variable<?>> variables) {
// // do nothing
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Constant<?> other = (Constant<?>) obj;
// if (this.type != other.type && (this.type == null || !this.type.equals(other.type))) {
// return false;
// }
// if ((this.value == null) ? (other.value != null) : !this.value.equals(other.value)) {
// return false;
// }
// return true;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 47 * hash + (this.type != null ? this.type.hashCode() : 0);
// hash = 47 * hash + (this.value != null ? this.value.hashCode() : 0);
// return hash;
// }
//
//
// @Override
// public Type<E> getType() {
// return this.type;
// }
//
// public E getValue() {
// return this.value;
// }
//
//
// @Override
// public Expression<?>[] getChildren() {
// return NO_CHILDREN;
// }
//
//
// @Override
// public Expression<E> duplicate(Expression<?>[] newChildren) {
// assert newChildren.length == 0;
// return this;
// }
//
//
// @Override
// public void print(Appendable a, int flags) throws IOException {
// a.append(String.valueOf(value));
// }
//
// @Override
// public void printMalformedExpression(Appendable a, int flags)
// throws IOException {
// if(value == null){
// a.append("null");
// } else {
// a.append(String.valueOf(value));
// }
// }
// @Override
// public <R, D> R accept(ExpressionVisitor<R, D> visitor, D data) {
// return visitor.visit(this, data);
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Constant(Class<E> clazz, E value) {
// this(ObjectConstraints.getPrimitiveType(clazz), value);
// }
// }
| import gov.nasa.jpf.constraints.expressions.Constant;
import java.util.Map; | public static <E> ValuationEntry<E> create(Variable<E> variable, E value) {
return new ValuationEntry<E>(variable, value);
}
private final Variable<E> variable;
private E value;
public ValuationEntry(Variable<E> variable, E value) {
this.variable = variable;
this.value = value;
}
public Variable<E> getVariable() {
return variable;
}
public E getValue() {
return value;
}
public void setValue(E value) {
this.value = value;
}
@Override
public ValuationEntry<E> clone() {
return new ValuationEntry<E>(variable, value);
}
| // Path: src/main/java/gov/nasa/jpf/constraints/expressions/Constant.java
// public class Constant<E> extends AbstractExpression<E> {
//
// public static <E> Constant<E> create(Type<E> type, E value) {
// return new Constant<E>(type, value);
// }
//
// public static <E> Constant<E> createParsed(Type<E> type, String txt) {
// return new Constant<E>(type, type.parse(txt));
// }
//
// public static <E> Constant<E> createCasted(Type<E> type, Object value) {
// return new Constant<E>(type, type.cast(value));
// }
//
// private final Type<E> type;
// private final E value;
//
// public Constant(Type<E> type, E value) {
// this.type = type;
// this.value = value;
// }
//
//
// @Override
// public E evaluate(Valuation values) {
// return this.value;
// }
//
//
// @Override
// public void collectFreeVariables(Collection<? super Variable<?>> variables) {
// // do nothing
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Constant<?> other = (Constant<?>) obj;
// if (this.type != other.type && (this.type == null || !this.type.equals(other.type))) {
// return false;
// }
// if ((this.value == null) ? (other.value != null) : !this.value.equals(other.value)) {
// return false;
// }
// return true;
// }
//
// @Override
// public int hashCode() {
// int hash = 7;
// hash = 47 * hash + (this.type != null ? this.type.hashCode() : 0);
// hash = 47 * hash + (this.value != null ? this.value.hashCode() : 0);
// return hash;
// }
//
//
// @Override
// public Type<E> getType() {
// return this.type;
// }
//
// public E getValue() {
// return this.value;
// }
//
//
// @Override
// public Expression<?>[] getChildren() {
// return NO_CHILDREN;
// }
//
//
// @Override
// public Expression<E> duplicate(Expression<?>[] newChildren) {
// assert newChildren.length == 0;
// return this;
// }
//
//
// @Override
// public void print(Appendable a, int flags) throws IOException {
// a.append(String.valueOf(value));
// }
//
// @Override
// public void printMalformedExpression(Appendable a, int flags)
// throws IOException {
// if(value == null){
// a.append("null");
// } else {
// a.append(String.valueOf(value));
// }
// }
// @Override
// public <R, D> R accept(ExpressionVisitor<R, D> visitor, D data) {
// return visitor.visit(this, data);
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Constant(Class<E> clazz, E value) {
// this(ObjectConstraints.getPrimitiveType(clazz), value);
// }
// }
// Path: src/main/java/gov/nasa/jpf/constraints/api/ValuationEntry.java
import gov.nasa.jpf.constraints.expressions.Constant;
import java.util.Map;
public static <E> ValuationEntry<E> create(Variable<E> variable, E value) {
return new ValuationEntry<E>(variable, value);
}
private final Variable<E> variable;
private E value;
public ValuationEntry(Variable<E> variable, E value) {
this.variable = variable;
this.value = value;
}
public Variable<E> getVariable() {
return variable;
}
public E getValue() {
return value;
}
public void setValue(E value) {
this.value = value;
}
@Override
public ValuationEntry<E> clone() {
return new ValuationEntry<E>(variable, value);
}
| public Constant<E> valueConstant() { |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/types/Type.java | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
| import gov.nasa.jpf.constraints.casts.CastOperation; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.types;
public interface Type<T> {
public String getName();
public String[] getOtherNames();
public Class<T> getCanonicalClass();
public Class<?>[] getOtherClasses();
public T cast(Object other);
public T getDefaultValue();
public Type<?> getSuperType();
| // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
// Path: src/main/java/gov/nasa/jpf/constraints/types/Type.java
import gov.nasa.jpf.constraints.casts.CastOperation;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.types;
public interface Type<T> {
public String getName();
public String[] getOtherNames();
public Class<T> getCanonicalClass();
public Class<?>[] getOtherClasses();
public T cast(Object other);
public T getDefaultValue();
public Type<?> getSuperType();
| public <O> CastOperation<? super O,? extends T> cast(Type<O> fromType); |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/solvers/dontknow/DontKnowSolverProvider.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/ConstraintSolverProvider.java
// public interface ConstraintSolverProvider {
// public String[] getNames();
// public ConstraintSolver createSolver(Properties config);
// }
| import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.solvers.ConstraintSolverProvider;
import java.util.Properties; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers.dontknow;
public class DontKnowSolverProvider implements ConstraintSolverProvider {
@Override
public String[] getNames() {
return new String[] {"dontknow"};
}
@Override | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/ConstraintSolverProvider.java
// public interface ConstraintSolverProvider {
// public String[] getNames();
// public ConstraintSolver createSolver(Properties config);
// }
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/dontknow/DontKnowSolverProvider.java
import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.solvers.ConstraintSolverProvider;
import java.util.Properties;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers.dontknow;
public class DontKnowSolverProvider implements ConstraintSolverProvider {
@Override
public String[] getNames() {
return new String[] {"dontknow"};
}
@Override | public ConstraintSolver createSolver(Properties config) { |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/types/ConcreteType.java | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
| import gov.nasa.jpf.constraints.casts.CastOperation; | /* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getOtherClasses()
*/
@Override
public Class<?>[] getOtherClasses() {
return otherClasses.clone(); // defensive copy
}
/* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getDefaultValue()
*/
@Override
public T getDefaultValue() {
return defaultValue;
}
/* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getSuperType()
*/
@Override
public Type<?> getSuperType() {
return superType;
}
@Override | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
// Path: src/main/java/gov/nasa/jpf/constraints/types/ConcreteType.java
import gov.nasa.jpf.constraints.casts.CastOperation;
/* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getOtherClasses()
*/
@Override
public Class<?>[] getOtherClasses() {
return otherClasses.clone(); // defensive copy
}
/* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getDefaultValue()
*/
@Override
public T getDefaultValue() {
return defaultValue;
}
/* (non-Javadoc)
* @see gov.nasa.jpf.constraints.types.Type#getSuperType()
*/
@Override
public Type<?> getSuperType() {
return superType;
}
@Override | public <O> CastOperation<? super O, ? extends T> cast(Type<O> fromType) { |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/solvers/ConstraintSolverProvider.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
| import gov.nasa.jpf.constraints.api.ConstraintSolver;
import java.util.Properties; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers;
/**
* A constraint solver provider.
*/
public interface ConstraintSolverProvider {
public String[] getNames(); | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/ConstraintSolverProvider.java
import gov.nasa.jpf.constraints.api.ConstraintSolver;
import java.util.Properties;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers;
/**
* A constraint solver provider.
*/
public interface ConstraintSolverProvider {
public String[] getNames(); | public ConstraintSolver createSolver(Properties config); |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/types/BuiltinTypes.java | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/casts/NumericCastOperation.java
// public abstract class NumericCastOperation<T extends Number> implements CastOperation<Number,T> {
//
// private final Class<T> toClass;
//
// public NumericCastOperation(Class<T> toClass) {
// this.toClass = toClass;
// }
//
// public static final NumericCastOperation<Byte> TO_SINT8 = new NumericCastOperation<Byte>(Byte.class) {
// @Override
// public Byte cast(Number from) {
// return from.byteValue();
// }
// };
// public static final NumericCastOperation<Short> TO_SINT16 = new NumericCastOperation<Short>(Short.class) {
// @Override
// public Short cast(Number from) {
// return from.shortValue();
// }
// };
// public static final NumericCastOperation<Integer> TO_SINT32 = new NumericCastOperation<Integer>(Integer.class) {
// @Override
// public Integer cast(Number from) {
// return from.intValue();
// }
// };
// public static final NumericCastOperation<Long> TO_SINT64 = new NumericCastOperation<Long>(Long.class) {
// @Override
// public Long cast(Number from) {
// return from.longValue();
// }
// };
// public static final NumericCastOperation<Float> TO_FLOAT = new NumericCastOperation<Float>(Float.class) {
// @Override
// public Float cast(Number from) {
// return from.floatValue();
// }
// };
// public static final NumericCastOperation<Double> TO_DOUBLE = new NumericCastOperation<Double>(Double.class) {
// @Override
// public Double cast(Number from) {
// return from.doubleValue();
// }
// };
//
// public static final NumericCastOperation<BigInteger> TO_INTEGER = new NumericCastOperation<BigInteger>(BigInteger.class) {
// @Override
// public BigInteger cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigInteger.class)
// return (BigInteger)from;
// if(clazz == BigDecimal.class)
// return ((BigDecimal)from).toBigInteger();
// else if(clazz == Double.class || clazz == Float.class)
// return BigDecimal.valueOf(from.doubleValue()).toBigInteger();
// return BigInteger.valueOf(from.longValue());
// }
// };
//
// public static final NumericCastOperation<BigDecimal> TO_DECIMAL = new NumericCastOperation<BigDecimal>(BigDecimal.class) {
// @Override
// public BigDecimal cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigDecimal.class)
// return (BigDecimal)from;
// if(clazz == BigInteger.class)
// return new BigDecimal((BigInteger)from);
// if(clazz == Long.class)
// return new BigDecimal(from.longValue());
// return new BigDecimal(from.doubleValue());
// }
// };
//
// public Class<Number> getFromClass() {
// return Number.class;
// }
//
// public Class<T> getToClass() {
// return toClass;
// }
//
// }
| import gov.nasa.jpf.constraints.casts.CastOperation;
import gov.nasa.jpf.constraints.casts.NumericCastOperation;
import java.math.BigDecimal;
import java.math.BigInteger; |
@Override
public Byte mul(Byte left, Byte right) {
return (byte)(left * right);
}
@Override
public Byte div(Byte left, Byte right) {
return (byte)(left / right);
}
@Override
public Byte mod(Byte left, Byte right) {
return (byte)(left % right);
}
@Override
public BigInteger integerValue(Byte value) {
return BigInteger.valueOf(value.intValue());
}
@Override
public Byte cast(Object other) {
if(other instanceof Number)
return ((Number)other).byteValue();
throw new ClassCastException();
}
@Override
@SuppressWarnings("unchecked") | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/casts/NumericCastOperation.java
// public abstract class NumericCastOperation<T extends Number> implements CastOperation<Number,T> {
//
// private final Class<T> toClass;
//
// public NumericCastOperation(Class<T> toClass) {
// this.toClass = toClass;
// }
//
// public static final NumericCastOperation<Byte> TO_SINT8 = new NumericCastOperation<Byte>(Byte.class) {
// @Override
// public Byte cast(Number from) {
// return from.byteValue();
// }
// };
// public static final NumericCastOperation<Short> TO_SINT16 = new NumericCastOperation<Short>(Short.class) {
// @Override
// public Short cast(Number from) {
// return from.shortValue();
// }
// };
// public static final NumericCastOperation<Integer> TO_SINT32 = new NumericCastOperation<Integer>(Integer.class) {
// @Override
// public Integer cast(Number from) {
// return from.intValue();
// }
// };
// public static final NumericCastOperation<Long> TO_SINT64 = new NumericCastOperation<Long>(Long.class) {
// @Override
// public Long cast(Number from) {
// return from.longValue();
// }
// };
// public static final NumericCastOperation<Float> TO_FLOAT = new NumericCastOperation<Float>(Float.class) {
// @Override
// public Float cast(Number from) {
// return from.floatValue();
// }
// };
// public static final NumericCastOperation<Double> TO_DOUBLE = new NumericCastOperation<Double>(Double.class) {
// @Override
// public Double cast(Number from) {
// return from.doubleValue();
// }
// };
//
// public static final NumericCastOperation<BigInteger> TO_INTEGER = new NumericCastOperation<BigInteger>(BigInteger.class) {
// @Override
// public BigInteger cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigInteger.class)
// return (BigInteger)from;
// if(clazz == BigDecimal.class)
// return ((BigDecimal)from).toBigInteger();
// else if(clazz == Double.class || clazz == Float.class)
// return BigDecimal.valueOf(from.doubleValue()).toBigInteger();
// return BigInteger.valueOf(from.longValue());
// }
// };
//
// public static final NumericCastOperation<BigDecimal> TO_DECIMAL = new NumericCastOperation<BigDecimal>(BigDecimal.class) {
// @Override
// public BigDecimal cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigDecimal.class)
// return (BigDecimal)from;
// if(clazz == BigInteger.class)
// return new BigDecimal((BigInteger)from);
// if(clazz == Long.class)
// return new BigDecimal(from.longValue());
// return new BigDecimal(from.doubleValue());
// }
// };
//
// public Class<Number> getFromClass() {
// return Number.class;
// }
//
// public Class<T> getToClass() {
// return toClass;
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/types/BuiltinTypes.java
import gov.nasa.jpf.constraints.casts.CastOperation;
import gov.nasa.jpf.constraints.casts.NumericCastOperation;
import java.math.BigDecimal;
import java.math.BigInteger;
@Override
public Byte mul(Byte left, Byte right) {
return (byte)(left * right);
}
@Override
public Byte div(Byte left, Byte right) {
return (byte)(left / right);
}
@Override
public Byte mod(Byte left, Byte right) {
return (byte)(left % right);
}
@Override
public BigInteger integerValue(Byte value) {
return BigInteger.valueOf(value.intValue());
}
@Override
public Byte cast(Object other) {
if(other instanceof Number)
return ((Number)other).byteValue();
throw new ClassCastException();
}
@Override
@SuppressWarnings("unchecked") | protected <O> CastOperation<? super O, ? extends Byte> castFrom( |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/types/BuiltinTypes.java | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/casts/NumericCastOperation.java
// public abstract class NumericCastOperation<T extends Number> implements CastOperation<Number,T> {
//
// private final Class<T> toClass;
//
// public NumericCastOperation(Class<T> toClass) {
// this.toClass = toClass;
// }
//
// public static final NumericCastOperation<Byte> TO_SINT8 = new NumericCastOperation<Byte>(Byte.class) {
// @Override
// public Byte cast(Number from) {
// return from.byteValue();
// }
// };
// public static final NumericCastOperation<Short> TO_SINT16 = new NumericCastOperation<Short>(Short.class) {
// @Override
// public Short cast(Number from) {
// return from.shortValue();
// }
// };
// public static final NumericCastOperation<Integer> TO_SINT32 = new NumericCastOperation<Integer>(Integer.class) {
// @Override
// public Integer cast(Number from) {
// return from.intValue();
// }
// };
// public static final NumericCastOperation<Long> TO_SINT64 = new NumericCastOperation<Long>(Long.class) {
// @Override
// public Long cast(Number from) {
// return from.longValue();
// }
// };
// public static final NumericCastOperation<Float> TO_FLOAT = new NumericCastOperation<Float>(Float.class) {
// @Override
// public Float cast(Number from) {
// return from.floatValue();
// }
// };
// public static final NumericCastOperation<Double> TO_DOUBLE = new NumericCastOperation<Double>(Double.class) {
// @Override
// public Double cast(Number from) {
// return from.doubleValue();
// }
// };
//
// public static final NumericCastOperation<BigInteger> TO_INTEGER = new NumericCastOperation<BigInteger>(BigInteger.class) {
// @Override
// public BigInteger cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigInteger.class)
// return (BigInteger)from;
// if(clazz == BigDecimal.class)
// return ((BigDecimal)from).toBigInteger();
// else if(clazz == Double.class || clazz == Float.class)
// return BigDecimal.valueOf(from.doubleValue()).toBigInteger();
// return BigInteger.valueOf(from.longValue());
// }
// };
//
// public static final NumericCastOperation<BigDecimal> TO_DECIMAL = new NumericCastOperation<BigDecimal>(BigDecimal.class) {
// @Override
// public BigDecimal cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigDecimal.class)
// return (BigDecimal)from;
// if(clazz == BigInteger.class)
// return new BigDecimal((BigInteger)from);
// if(clazz == Long.class)
// return new BigDecimal(from.longValue());
// return new BigDecimal(from.doubleValue());
// }
// };
//
// public Class<Number> getFromClass() {
// return Number.class;
// }
//
// public Class<T> getToClass() {
// return toClass;
// }
//
// }
| import gov.nasa.jpf.constraints.casts.CastOperation;
import gov.nasa.jpf.constraints.casts.NumericCastOperation;
import java.math.BigDecimal;
import java.math.BigInteger; | return (byte)(left * right);
}
@Override
public Byte div(Byte left, Byte right) {
return (byte)(left / right);
}
@Override
public Byte mod(Byte left, Byte right) {
return (byte)(left % right);
}
@Override
public BigInteger integerValue(Byte value) {
return BigInteger.valueOf(value.intValue());
}
@Override
public Byte cast(Object other) {
if(other instanceof Number)
return ((Number)other).byteValue();
throw new ClassCastException();
}
@Override
@SuppressWarnings("unchecked")
protected <O> CastOperation<? super O, ? extends Byte> castFrom(
Type<O> other) {
if(Number.class.isAssignableFrom(other.getCanonicalClass())) | // Path: src/main/java/gov/nasa/jpf/constraints/casts/CastOperation.java
// public interface CastOperation<F, T> {
// public Class<F> getFromClass();
// public Class<T> getToClass();
//
// public T cast(F from);
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/casts/NumericCastOperation.java
// public abstract class NumericCastOperation<T extends Number> implements CastOperation<Number,T> {
//
// private final Class<T> toClass;
//
// public NumericCastOperation(Class<T> toClass) {
// this.toClass = toClass;
// }
//
// public static final NumericCastOperation<Byte> TO_SINT8 = new NumericCastOperation<Byte>(Byte.class) {
// @Override
// public Byte cast(Number from) {
// return from.byteValue();
// }
// };
// public static final NumericCastOperation<Short> TO_SINT16 = new NumericCastOperation<Short>(Short.class) {
// @Override
// public Short cast(Number from) {
// return from.shortValue();
// }
// };
// public static final NumericCastOperation<Integer> TO_SINT32 = new NumericCastOperation<Integer>(Integer.class) {
// @Override
// public Integer cast(Number from) {
// return from.intValue();
// }
// };
// public static final NumericCastOperation<Long> TO_SINT64 = new NumericCastOperation<Long>(Long.class) {
// @Override
// public Long cast(Number from) {
// return from.longValue();
// }
// };
// public static final NumericCastOperation<Float> TO_FLOAT = new NumericCastOperation<Float>(Float.class) {
// @Override
// public Float cast(Number from) {
// return from.floatValue();
// }
// };
// public static final NumericCastOperation<Double> TO_DOUBLE = new NumericCastOperation<Double>(Double.class) {
// @Override
// public Double cast(Number from) {
// return from.doubleValue();
// }
// };
//
// public static final NumericCastOperation<BigInteger> TO_INTEGER = new NumericCastOperation<BigInteger>(BigInteger.class) {
// @Override
// public BigInteger cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigInteger.class)
// return (BigInteger)from;
// if(clazz == BigDecimal.class)
// return ((BigDecimal)from).toBigInteger();
// else if(clazz == Double.class || clazz == Float.class)
// return BigDecimal.valueOf(from.doubleValue()).toBigInteger();
// return BigInteger.valueOf(from.longValue());
// }
// };
//
// public static final NumericCastOperation<BigDecimal> TO_DECIMAL = new NumericCastOperation<BigDecimal>(BigDecimal.class) {
// @Override
// public BigDecimal cast(Number from) {
// Class<?> clazz = from.getClass();
// if(clazz == BigDecimal.class)
// return (BigDecimal)from;
// if(clazz == BigInteger.class)
// return new BigDecimal((BigInteger)from);
// if(clazz == Long.class)
// return new BigDecimal(from.longValue());
// return new BigDecimal(from.doubleValue());
// }
// };
//
// public Class<Number> getFromClass() {
// return Number.class;
// }
//
// public Class<T> getToClass() {
// return toClass;
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/types/BuiltinTypes.java
import gov.nasa.jpf.constraints.casts.CastOperation;
import gov.nasa.jpf.constraints.casts.NumericCastOperation;
import java.math.BigDecimal;
import java.math.BigInteger;
return (byte)(left * right);
}
@Override
public Byte div(Byte left, Byte right) {
return (byte)(left / right);
}
@Override
public Byte mod(Byte left, Byte right) {
return (byte)(left % right);
}
@Override
public BigInteger integerValue(Byte value) {
return BigInteger.valueOf(value.intValue());
}
@Override
public Byte cast(Object other) {
if(other instanceof Number)
return ((Number)other).byteValue();
throw new ClassCastException();
}
@Override
@SuppressWarnings("unchecked")
protected <O> CastOperation<? super O, ? extends Byte> castFrom(
Type<O> other) {
if(Number.class.isAssignableFrom(other.getCanonicalClass())) | return (CastOperation<? super O,? extends Byte>)NumericCastOperation.TO_SINT8; |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/solvers/ReflectionSolverProvider.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/exceptions/SolverCreationException.java
// public class SolverCreationException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// public SolverCreationException() {
// }
//
// public SolverCreationException(String message) {
// super(message);
// }
//
// public SolverCreationException(Throwable cause) {
// super(cause);
// }
//
// public SolverCreationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.exceptions.SolverCreationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers;
final class ReflectionSolverProvider implements ConstraintSolverProvider {
private static final Logger logger = Logger.getLogger("constraints");
| // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/exceptions/SolverCreationException.java
// public class SolverCreationException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// public SolverCreationException() {
// }
//
// public SolverCreationException(String message) {
// super(message);
// }
//
// public SolverCreationException(Throwable cause) {
// super(cause);
// }
//
// public SolverCreationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/ReflectionSolverProvider.java
import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.exceptions.SolverCreationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.solvers;
final class ReflectionSolverProvider implements ConstraintSolverProvider {
private static final Logger logger = Logger.getLogger("constraints");
| private final Constructor<? extends ConstraintSolver> ctor; |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/solvers/ReflectionSolverProvider.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/exceptions/SolverCreationException.java
// public class SolverCreationException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// public SolverCreationException() {
// }
//
// public SolverCreationException(String message) {
// super(message);
// }
//
// public SolverCreationException(Throwable cause) {
// super(cause);
// }
//
// public SolverCreationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.exceptions.SolverCreationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger; | catch(NoSuchMethodException ex) {
throw new IllegalArgumentException("Constraint solver class " + clazz.getName()
+ " neither exposes Properties nor default constructor");
}
catch(SecurityException ex) {
throw new IllegalArgumentException("Constraint solver class " + clazz.getName()
+ " neither exposes Properties nor default constructor");
}
}
this.ctor = ctor;
this.hasPropertyCtor = hasPropertyCtor;
}
@Override
public String[] getNames() {
Class<?> declClazz = ctor.getDeclaringClass();
return new String[]{declClazz.getSimpleName(), declClazz.getName()};
}
@Override
public ConstraintSolver createSolver(Properties config) {
try {
if(hasPropertyCtor)
return ctor.newInstance(config);
logger.log(Level.FINE, "Note: {0} does not expose a " +
"Properties constructor. No configuration is used.", ctor.getDeclaringClass().getName());
return ctor.newInstance();
}
catch(IllegalAccessException ex) { | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public abstract class ConstraintSolver {
//
// /**
// * result returned by a constraint solver
// *
// */
// public static enum Result {SAT,UNSAT,DONT_KNOW};
//
// /**
// * runs f by the constraint solver and returns if
// * f can be satisfied
// *
// * @param f formula to check for satisfiability
// * @return the satisfiability {@link Result}
// */
// public Result isSatisfiable(Expression<Boolean> f) {
// return solve(f, new Valuation());
// }
//
//
// /**
// * solves f and returns a satisfying solution
// *
// * @param f
// * @param result solution that satisfies f or null in case of only checking for satisfiability
// * @return the satisfiability {@link Result}
// */
// public abstract Result solve(Expression<Boolean> f, Valuation result);
//
// /**
// * Create a solver context, which allows for incremental solving (i.e., via push and pop).
// * This is an optional operation.
// * @return a solver context
// * @throws UnsupportedOperationException if the solver engine does not incremental solving
// */
// public SolverContext createContext() {
// throw new UnsupportedOperationException("Solver does not support incremental solving");
// }
//
//
// // LEGACY API
//
// @Deprecated
// public Result isSatisfiable(Expression<Boolean> f, MinMax m) {
// return solve(f, m, new Valuation());
// }
//
// @Deprecated
// public Result solve(Expression<Boolean> f, MinMax m, Valuation val) {
// //Expression<Boolean> mod = m.apply(f);
// return solve(f, val);
// }
//
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/exceptions/SolverCreationException.java
// public class SolverCreationException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// public SolverCreationException() {
// }
//
// public SolverCreationException(String message) {
// super(message);
// }
//
// public SolverCreationException(Throwable cause) {
// super(cause);
// }
//
// public SolverCreationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/solvers/ReflectionSolverProvider.java
import gov.nasa.jpf.constraints.api.ConstraintSolver;
import gov.nasa.jpf.constraints.exceptions.SolverCreationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
catch(NoSuchMethodException ex) {
throw new IllegalArgumentException("Constraint solver class " + clazz.getName()
+ " neither exposes Properties nor default constructor");
}
catch(SecurityException ex) {
throw new IllegalArgumentException("Constraint solver class " + clazz.getName()
+ " neither exposes Properties nor default constructor");
}
}
this.ctor = ctor;
this.hasPropertyCtor = hasPropertyCtor;
}
@Override
public String[] getNames() {
Class<?> declClazz = ctor.getDeclaringClass();
return new String[]{declClazz.getSimpleName(), declClazz.getName()};
}
@Override
public ConstraintSolver createSolver(Properties config) {
try {
if(hasPropertyCtor)
return ctor.newInstance(config);
logger.log(Level.FINE, "Note: {0} does not expose a " +
"Properties constructor. No configuration is used.", ctor.getDeclaringClass().getName());
return ctor.newInstance();
}
catch(IllegalAccessException ex) { | throw new SolverCreationException(ex); |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/api/SolverContext.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public static enum Result {SAT,UNSAT,DONT_KNOW};
| import gov.nasa.jpf.constraints.api.ConstraintSolver.Result;
import java.util.Arrays;
import java.util.List; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.api;
/**
* Solver context to support incremental solving (i.e., with backtracking).
*/
public abstract class SolverContext {
public abstract void push();
public abstract void pop(int n);
public void pop() {
pop(1);
}
| // Path: src/main/java/gov/nasa/jpf/constraints/api/ConstraintSolver.java
// public static enum Result {SAT,UNSAT,DONT_KNOW};
// Path: src/main/java/gov/nasa/jpf/constraints/api/SolverContext.java
import gov.nasa.jpf.constraints.api.ConstraintSolver.Result;
import java.util.Arrays;
import java.util.List;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.api;
/**
* Solver context to support incremental solving (i.e., with backtracking).
*/
public abstract class SolverContext {
public abstract void push();
public abstract void pop(int n);
public void pop() {
pop(1);
}
| public Result isSatisfiable() { |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/util/ExpressionSimplifier.java | // Path: src/main/java/gov/nasa/jpf/constraints/api/Expression.java
// public abstract class Expression<E> extends AbstractPrintable {
//
//
// public static final int QUOTE_IDENTIFIERS = 1;
// public static final int INCLUDE_VARIABLE_TYPE = 2;
// public static final int INCLUDE_BOUND_DECL_TYPE = 4;
// public static final int SIMPLE_PROP_OPERATORS = 8;
//
// public static final int DEFAULT_FLAGS = QUOTE_IDENTIFIERS | INCLUDE_BOUND_DECL_TYPE;
//
// public static final int JAVA_COMPAT_FLAGS = SIMPLE_PROP_OPERATORS;
//
// public static boolean quoteIdentifiers(int printFlags) {
// return (printFlags & QUOTE_IDENTIFIERS) == QUOTE_IDENTIFIERS;
// }
//
// public static boolean includeVariableType(int printFlags) {
// return (printFlags & INCLUDE_VARIABLE_TYPE) == INCLUDE_VARIABLE_TYPE;
// }
//
// public static boolean includeBoundDeclType(int printFlags) {
// return (printFlags & INCLUDE_BOUND_DECL_TYPE) == INCLUDE_BOUND_DECL_TYPE;
// }
//
// public static Expression<?>[] NO_CHILDREN = new Expression[0];
//
//
// /**
// * evaluates using the provided values for symbolic variables
// *
// * @param values
// * @return
// */
// public abstract E evaluate(Valuation values);
//
// /**
// * collect all symbolic variables
// *
// * @param names
// */
// public abstract void collectFreeVariables(Collection<? super Variable<?>> variables);
//
// public abstract <R,D> R accept(ExpressionVisitor<R, D> visitor, D data);
//
//
// public abstract Type<E> getType();
//
// public Class<E> getResultType() {
// return getType().getCanonicalClass();
// }
//
//
// public abstract Expression<?>[] getChildren();
// public abstract Expression<?> duplicate(Expression<?>[] newChildren);
//
// @SuppressWarnings("unchecked")
// public <F> Expression<F> as(Type<F> type) {
// Type<E> thisType = getType();
// if(!thisType.equals(type))
// return null;
// return (Expression<F>)this;
// }
//
// public <F> Expression<F> requireAs(Type<F> type) {
// Expression<F> exp = as(type);
// if(exp == null)
// throw new IllegalArgumentException("Expected type " + type + ", is " + getType());
// return exp;
// }
//
// public abstract void print(Appendable a, int flags) throws IOException;
//
// /**A malformed Expression might contain a null value.
// This method should only be used in debug environment
// * @throws java.io.IOExceptions*/
// public abstract void printMalformedExpression(Appendable a, int flags)
// throws IOException;
//
// public String toString(int flags) {
// StringBuilder sb = new StringBuilder();
// try {
// print(sb, flags);
// return sb.toString();
// }
// catch(IOException ex) {
// throw new RuntimeException("Unexpected IOException writing to StringBuilder");
// }
// }
//
// @Override
// public final void print(Appendable a) throws IOException {
// print(a, DEFAULT_FLAGS);
// }
//
// public final void printMalformedExpression(Appendable a) throws IOException {
// printMalformedExpression(a, DEFAULT_FLAGS);
// }
//
//
// // LEGACY API
//
// /**
// * replace terms according to replace
// *
// * @param replace
// * @return
// */
// @Deprecated
// @SuppressWarnings("rawtypes")
// public Expression replaceTerms(Map<Expression,Expression> replacements) {
// Expression<?> rep = replacements.get(this);
// if(rep != null)
// return rep;
// Expression<?>[] children = getChildren();
//
// boolean changed = false;
// for(int i = 0; i < children.length; i++) {
// Expression<?> old = children[i];
// Expression<?> newExp = old.replaceTerms(replacements);
// if(old != newExp)
// changed = true;
// children[i] = newExp;
// }
//
// if(!changed)
// return this;
//
// return duplicate(children);
// }
//
// @Deprecated
// @SuppressWarnings("rawtypes")
// public void getVariables(Set<Variable> variables) {
// collectFreeVariables(variables);
// }
//
// }
| import gov.nasa.jpf.constraints.api.Expression; | /*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.util;
@Deprecated
public class ExpressionSimplifier {
public ExpressionSimplifier() {
}
@SuppressWarnings({"rawtypes","unchecked"}) | // Path: src/main/java/gov/nasa/jpf/constraints/api/Expression.java
// public abstract class Expression<E> extends AbstractPrintable {
//
//
// public static final int QUOTE_IDENTIFIERS = 1;
// public static final int INCLUDE_VARIABLE_TYPE = 2;
// public static final int INCLUDE_BOUND_DECL_TYPE = 4;
// public static final int SIMPLE_PROP_OPERATORS = 8;
//
// public static final int DEFAULT_FLAGS = QUOTE_IDENTIFIERS | INCLUDE_BOUND_DECL_TYPE;
//
// public static final int JAVA_COMPAT_FLAGS = SIMPLE_PROP_OPERATORS;
//
// public static boolean quoteIdentifiers(int printFlags) {
// return (printFlags & QUOTE_IDENTIFIERS) == QUOTE_IDENTIFIERS;
// }
//
// public static boolean includeVariableType(int printFlags) {
// return (printFlags & INCLUDE_VARIABLE_TYPE) == INCLUDE_VARIABLE_TYPE;
// }
//
// public static boolean includeBoundDeclType(int printFlags) {
// return (printFlags & INCLUDE_BOUND_DECL_TYPE) == INCLUDE_BOUND_DECL_TYPE;
// }
//
// public static Expression<?>[] NO_CHILDREN = new Expression[0];
//
//
// /**
// * evaluates using the provided values for symbolic variables
// *
// * @param values
// * @return
// */
// public abstract E evaluate(Valuation values);
//
// /**
// * collect all symbolic variables
// *
// * @param names
// */
// public abstract void collectFreeVariables(Collection<? super Variable<?>> variables);
//
// public abstract <R,D> R accept(ExpressionVisitor<R, D> visitor, D data);
//
//
// public abstract Type<E> getType();
//
// public Class<E> getResultType() {
// return getType().getCanonicalClass();
// }
//
//
// public abstract Expression<?>[] getChildren();
// public abstract Expression<?> duplicate(Expression<?>[] newChildren);
//
// @SuppressWarnings("unchecked")
// public <F> Expression<F> as(Type<F> type) {
// Type<E> thisType = getType();
// if(!thisType.equals(type))
// return null;
// return (Expression<F>)this;
// }
//
// public <F> Expression<F> requireAs(Type<F> type) {
// Expression<F> exp = as(type);
// if(exp == null)
// throw new IllegalArgumentException("Expected type " + type + ", is " + getType());
// return exp;
// }
//
// public abstract void print(Appendable a, int flags) throws IOException;
//
// /**A malformed Expression might contain a null value.
// This method should only be used in debug environment
// * @throws java.io.IOExceptions*/
// public abstract void printMalformedExpression(Appendable a, int flags)
// throws IOException;
//
// public String toString(int flags) {
// StringBuilder sb = new StringBuilder();
// try {
// print(sb, flags);
// return sb.toString();
// }
// catch(IOException ex) {
// throw new RuntimeException("Unexpected IOException writing to StringBuilder");
// }
// }
//
// @Override
// public final void print(Appendable a) throws IOException {
// print(a, DEFAULT_FLAGS);
// }
//
// public final void printMalformedExpression(Appendable a) throws IOException {
// printMalformedExpression(a, DEFAULT_FLAGS);
// }
//
//
// // LEGACY API
//
// /**
// * replace terms according to replace
// *
// * @param replace
// * @return
// */
// @Deprecated
// @SuppressWarnings("rawtypes")
// public Expression replaceTerms(Map<Expression,Expression> replacements) {
// Expression<?> rep = replacements.get(this);
// if(rep != null)
// return rep;
// Expression<?>[] children = getChildren();
//
// boolean changed = false;
// for(int i = 0; i < children.length; i++) {
// Expression<?> old = children[i];
// Expression<?> newExp = old.replaceTerms(replacements);
// if(old != newExp)
// changed = true;
// children[i] = newExp;
// }
//
// if(!changed)
// return this;
//
// return duplicate(children);
// }
//
// @Deprecated
// @SuppressWarnings("rawtypes")
// public void getVariables(Set<Variable> variables) {
// collectFreeVariables(variables);
// }
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/util/ExpressionSimplifier.java
import gov.nasa.jpf.constraints.api.Expression;
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jpf.constraints.util;
@Deprecated
public class ExpressionSimplifier {
public ExpressionSimplifier() {
}
@SuppressWarnings({"rawtypes","unchecked"}) | public Expression simplify(Expression e) { |
psycopaths/jconstraints | src/main/java/gov/nasa/jpf/constraints/api/Variable.java | // Path: src/main/java/gov/nasa/jpf/constraints/java/ObjectConstraints.java
// public class ObjectConstraints {
//
// private static final TypeContext javaTypes = new TypeContext(true);
//
//
// public static void addToValuation(String name, Object obj, Class<?> realClass, Valuation val) {
// if(realClass.isPrimitive()) {
// addPrimitiveToValuation(name, obj, val);
// }
// else {
// addInstanceToValuation(name, obj, Predicates.alwaysTrue(), val, new IdentityHashMap<Object,Boolean>());
// }
// }
//
// public static void addInstanceToValuation(String objName, Object obj, Predicate<? super Field> filter, Valuation val, IdentityHashMap<Object,Boolean> visited) {
// if(obj == null)
// return;
//
// if(visited.put(obj, Boolean.TRUE) != null)
// return;
//
// Field[] fields = obj.getClass().getFields();
//
//
// for(Field f : fields) {
// if(!filter.apply(f))
// continue;
//
// Class<?> ftype = f.getType();
// String fname = objName + "." + f.getName();
//
// try {
// Object value = f.get(obj);
//
// if(!ftype.isPrimitive()) {
// addInstanceToValuation(fname, value, filter, val, visited);
// }
// else {
// addPrimitiveToValuation(fname, value, val);
// }
// }
// catch(IllegalAccessException ex) {
// ex.printStackTrace();
// // IGNORE FIELD
// }
// }
// }
//
//
// public static void addPrimitiveToValuation(String name, Object value, Valuation val) {
// Variable<?> var = getPrimitiveVar(name, value.getClass());
// val.setCastedValue(var, value);
// }
//
// public static <T> Variable<T> getPrimitiveVar(String name, Class<T> clazz) {
// Type<T> t = getPrimitiveType(clazz);
// return Variable.create(t, name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constant<T> getPrimitiveConst(T value) {
// Type<T> t = getPrimitiveType((Class<T>)value.getClass());
// return Constant.create(t, value);
// }
//
//
// @SuppressWarnings("unchecked")
// public static <T> Type<T> getPrimitiveType(Class<T> clazz) {
// if(clazz == Boolean.class)
// return (Type<T>)BuiltinTypes.BOOL;
// if(clazz == Byte.class)
// return (Type<T>)BuiltinTypes.SINT8;
// if(clazz == Character.class)
// return (Type<T>)BuiltinTypes.UINT16;
// if(clazz == Short.class)
// return (Type<T>)BuiltinTypes.SINT16;
// if(clazz == Integer.class)
// return (Type<T>)BuiltinTypes.SINT32;
// if(clazz == Long.class)
// return (Type<T>)BuiltinTypes.SINT64;
// if(clazz == Float.class)
// return (Type<T>)BuiltinTypes.FLOAT;
// if(clazz == Double.class)
// return (Type<T>)BuiltinTypes.DOUBLE;
// throw new IllegalArgumentException("Class " + clazz.getName() + " is not a wrapper class for a primitive type");
// }
//
// public static TypeContext getJavaTypes() {
// return javaTypes;
// }
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/types/Type.java
// public interface Type<T> {
//
// public String getName();
//
// public String[] getOtherNames();
//
// public Class<T> getCanonicalClass();
//
// public Class<?>[] getOtherClasses();
//
// public T cast(Object other);
//
// public T getDefaultValue();
//
// public Type<?> getSuperType();
//
// public <O> CastOperation<? super O,? extends T> cast(Type<O> fromType);
// public <O> CastOperation<? super O,? extends T> requireCast(Type<O> fromType);
//
// public abstract T parse(String string);
//
//
//
// }
| import gov.nasa.jpf.constraints.java.ObjectConstraints;
import gov.nasa.jpf.constraints.types.Type;
import java.io.IOException;
import java.util.Collection; | }
if(qid)
a.append('\'');
if(includeVariableType(flags)) {
a.append(':');
if(type == null){
a.append("null");
} else {
a.append(type.getName());
}
}
}
@Override
public <R, D> R accept(ExpressionVisitor<R, D> visitor, D data) {
return visitor.visit(this, data);
}
public void printTyped(Appendable a) throws IOException {
print(a, DEFAULT_FLAGS | INCLUDE_VARIABLE_TYPE);
}
// LEGACY API
@Deprecated
public Variable(Class<E> clazz, String name) { | // Path: src/main/java/gov/nasa/jpf/constraints/java/ObjectConstraints.java
// public class ObjectConstraints {
//
// private static final TypeContext javaTypes = new TypeContext(true);
//
//
// public static void addToValuation(String name, Object obj, Class<?> realClass, Valuation val) {
// if(realClass.isPrimitive()) {
// addPrimitiveToValuation(name, obj, val);
// }
// else {
// addInstanceToValuation(name, obj, Predicates.alwaysTrue(), val, new IdentityHashMap<Object,Boolean>());
// }
// }
//
// public static void addInstanceToValuation(String objName, Object obj, Predicate<? super Field> filter, Valuation val, IdentityHashMap<Object,Boolean> visited) {
// if(obj == null)
// return;
//
// if(visited.put(obj, Boolean.TRUE) != null)
// return;
//
// Field[] fields = obj.getClass().getFields();
//
//
// for(Field f : fields) {
// if(!filter.apply(f))
// continue;
//
// Class<?> ftype = f.getType();
// String fname = objName + "." + f.getName();
//
// try {
// Object value = f.get(obj);
//
// if(!ftype.isPrimitive()) {
// addInstanceToValuation(fname, value, filter, val, visited);
// }
// else {
// addPrimitiveToValuation(fname, value, val);
// }
// }
// catch(IllegalAccessException ex) {
// ex.printStackTrace();
// // IGNORE FIELD
// }
// }
// }
//
//
// public static void addPrimitiveToValuation(String name, Object value, Valuation val) {
// Variable<?> var = getPrimitiveVar(name, value.getClass());
// val.setCastedValue(var, value);
// }
//
// public static <T> Variable<T> getPrimitiveVar(String name, Class<T> clazz) {
// Type<T> t = getPrimitiveType(clazz);
// return Variable.create(t, name);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constant<T> getPrimitiveConst(T value) {
// Type<T> t = getPrimitiveType((Class<T>)value.getClass());
// return Constant.create(t, value);
// }
//
//
// @SuppressWarnings("unchecked")
// public static <T> Type<T> getPrimitiveType(Class<T> clazz) {
// if(clazz == Boolean.class)
// return (Type<T>)BuiltinTypes.BOOL;
// if(clazz == Byte.class)
// return (Type<T>)BuiltinTypes.SINT8;
// if(clazz == Character.class)
// return (Type<T>)BuiltinTypes.UINT16;
// if(clazz == Short.class)
// return (Type<T>)BuiltinTypes.SINT16;
// if(clazz == Integer.class)
// return (Type<T>)BuiltinTypes.SINT32;
// if(clazz == Long.class)
// return (Type<T>)BuiltinTypes.SINT64;
// if(clazz == Float.class)
// return (Type<T>)BuiltinTypes.FLOAT;
// if(clazz == Double.class)
// return (Type<T>)BuiltinTypes.DOUBLE;
// throw new IllegalArgumentException("Class " + clazz.getName() + " is not a wrapper class for a primitive type");
// }
//
// public static TypeContext getJavaTypes() {
// return javaTypes;
// }
// }
//
// Path: src/main/java/gov/nasa/jpf/constraints/types/Type.java
// public interface Type<T> {
//
// public String getName();
//
// public String[] getOtherNames();
//
// public Class<T> getCanonicalClass();
//
// public Class<?>[] getOtherClasses();
//
// public T cast(Object other);
//
// public T getDefaultValue();
//
// public Type<?> getSuperType();
//
// public <O> CastOperation<? super O,? extends T> cast(Type<O> fromType);
// public <O> CastOperation<? super O,? extends T> requireCast(Type<O> fromType);
//
// public abstract T parse(String string);
//
//
//
// }
// Path: src/main/java/gov/nasa/jpf/constraints/api/Variable.java
import gov.nasa.jpf.constraints.java.ObjectConstraints;
import gov.nasa.jpf.constraints.types.Type;
import java.io.IOException;
import java.util.Collection;
}
if(qid)
a.append('\'');
if(includeVariableType(flags)) {
a.append(':');
if(type == null){
a.append("null");
} else {
a.append(type.getName());
}
}
}
@Override
public <R, D> R accept(ExpressionVisitor<R, D> visitor, D data) {
return visitor.visit(this, data);
}
public void printTyped(Appendable a) throws IOException {
print(a, DEFAULT_FLAGS | INCLUDE_VARIABLE_TYPE);
}
// LEGACY API
@Deprecated
public Variable(Class<E> clazz, String name) { | this(ObjectConstraints.getPrimitiveType(clazz), name); |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/SearchResult.java | // Path: src/main/java/com/codefork/refine/resources/Result.java
// public class Result {
//
// private String id;
// private String name;
//
// /**
// * It's weird that this is a list but that's what OpenRefine expects.
// * A VIAF result only ever has one type, but maybe other reconciliation
// * services return multiple types for a name?
// */
// private List<VIAFNameType> type;
// private double score;
// private boolean match;
//
// public Result(String id, String name, NameType nameType, double score, boolean match) {
// this.id = id;
// this.name = name;
// this.type = new ArrayList<VIAFNameType>();
// this.type.add(nameType.asVIAFNameType());
// this.score = score;
// this.match = match;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<VIAFNameType> getType() {
// return type;
// }
//
// public void setType(List<VIAFNameType> resultType) {
// this.type = resultType;
// }
//
// public double getScore() {
// return score;
// }
//
// public void setScore(double score) {
// this.score = score;
// }
//
// public boolean isMatch() {
// return match;
// }
//
// public void setMatch(boolean match) {
// this.match = match;
// }
//
// }
| import com.codefork.refine.resources.Result;
import java.util.List; | package com.codefork.refine;
/**
*/
public class SearchResult {
public enum ErrorType {
UNKNOWN, TOO_MANY_REQUESTS
};
private String key; | // Path: src/main/java/com/codefork/refine/resources/Result.java
// public class Result {
//
// private String id;
// private String name;
//
// /**
// * It's weird that this is a list but that's what OpenRefine expects.
// * A VIAF result only ever has one type, but maybe other reconciliation
// * services return multiple types for a name?
// */
// private List<VIAFNameType> type;
// private double score;
// private boolean match;
//
// public Result(String id, String name, NameType nameType, double score, boolean match) {
// this.id = id;
// this.name = name;
// this.type = new ArrayList<VIAFNameType>();
// this.type.add(nameType.asVIAFNameType());
// this.score = score;
// this.match = match;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<VIAFNameType> getType() {
// return type;
// }
//
// public void setType(List<VIAFNameType> resultType) {
// this.type = resultType;
// }
//
// public double getScore() {
// return score;
// }
//
// public void setScore(double score) {
// this.score = score;
// }
//
// public boolean isMatch() {
// return match;
// }
//
// public void setMatch(boolean match) {
// this.match = match;
// }
//
// }
// Path: src/main/java/com/codefork/refine/SearchResult.java
import com.codefork.refine.resources.Result;
import java.util.List;
package com.codefork.refine;
/**
*/
public class SearchResult {
public enum ErrorType {
UNKNOWN, TOO_MANY_REQUESTS
};
private String key; | private List<Result> results; |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java | // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
| import com.codefork.refine.Config;
import com.codefork.refine.NameType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List; | package com.codefork.refine.resources;
/**
* Metadata about this reconciliation service, operating in normal VIAF mode.
*/
public class ServiceMetaDataResponse {
Log log = LogFactory.getLog(ServiceMetaDataResponse.class);
public static class View {
private String url;
public View(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
private String name = "";
private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf";
private final static View VIEW = new View("http://viaf.org/viaf/{{id}}");
private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
private final static List<VIAFNameType> DEFAULT_TYPES = new ArrayList<VIAFNameType>();
static { | // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java
import com.codefork.refine.Config;
import com.codefork.refine.NameType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List;
package com.codefork.refine.resources;
/**
* Metadata about this reconciliation service, operating in normal VIAF mode.
*/
public class ServiceMetaDataResponse {
Log log = LogFactory.getLog(ServiceMetaDataResponse.class);
public static class View {
private String url;
public View(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
private String name = "";
private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf";
private final static View VIEW = new View("http://viaf.org/viaf/{{id}}");
private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
private final static List<VIAFNameType> DEFAULT_TYPES = new ArrayList<VIAFNameType>();
static { | for(NameType nameType : NameType.values()) { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java | // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
| import com.codefork.refine.Config;
import com.codefork.refine.NameType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List; | package com.codefork.refine.resources;
/**
* Metadata about this reconciliation service, operating in normal VIAF mode.
*/
public class ServiceMetaDataResponse {
Log log = LogFactory.getLog(ServiceMetaDataResponse.class);
public static class View {
private String url;
public View(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
private String name = "";
private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf";
private final static View VIEW = new View("http://viaf.org/viaf/{{id}}");
private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
private final static List<VIAFNameType> DEFAULT_TYPES = new ArrayList<VIAFNameType>();
static {
for(NameType nameType : NameType.values()) {
DEFAULT_TYPES.add(nameType.asVIAFNameType());
}
}
| // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java
import com.codefork.refine.Config;
import com.codefork.refine.NameType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List;
package com.codefork.refine.resources;
/**
* Metadata about this reconciliation service, operating in normal VIAF mode.
*/
public class ServiceMetaDataResponse {
Log log = LogFactory.getLog(ServiceMetaDataResponse.class);
public static class View {
private String url;
public View(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
private String name = "";
private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf";
private final static View VIEW = new View("http://viaf.org/viaf/{{id}}");
private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
private final static List<VIAFNameType> DEFAULT_TYPES = new ArrayList<VIAFNameType>();
static {
for(NameType nameType : NameType.values()) {
DEFAULT_TYPES.add(nameType.asVIAFNameType());
}
}
| public ServiceMetaDataResponse(Config config, String source) { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/resources/Result.java | // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
| import com.codefork.refine.NameType;
import java.util.ArrayList;
import java.util.List; |
package com.codefork.refine.resources;
/**
* A single name result. The JSON looks like this:
*
* {
* 'id' : '...',
* 'name': '...',
* 'type': [
* {
* "id": '...',
* "name": '...',
* },
* ],
* 'score': 1,
* 'match': true
* }
*/
public class Result {
private String id;
private String name;
/**
* It's weird that this is a list but that's what OpenRefine expects.
* A VIAF result only ever has one type, but maybe other reconciliation
* services return multiple types for a name?
*/
private List<VIAFNameType> type;
private double score;
private boolean match;
| // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/com/codefork/refine/resources/Result.java
import com.codefork.refine.NameType;
import java.util.ArrayList;
import java.util.List;
package com.codefork.refine.resources;
/**
* A single name result. The JSON looks like this:
*
* {
* 'id' : '...',
* 'name': '...',
* 'type': [
* {
* "id": '...',
* "name": '...',
* },
* ],
* 'score': 1,
* 'match': true
* }
*/
public class Result {
private String id;
private String name;
/**
* It's weird that this is a list but that's what OpenRefine expects.
* A VIAF result only ever has one type, but maybe other reconciliation
* services return multiple types for a name?
*/
private List<VIAFNameType> type;
private double score;
private boolean match;
| public Result(String id, String name, NameType nameType, double score, boolean match) { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/NameType.java | // Path: src/main/java/com/codefork/refine/resources/VIAFNameType.java
// public class VIAFNameType {
//
// private String id;
// private String name;
//
// public VIAFNameType(String id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj instanceof VIAFNameType) {
// VIAFNameType obj2 = (VIAFNameType) obj;
// return obj2.getId().equals(getId())
// && obj2.getName().equals(getName());
// }
// return false;
// }
// }
| import com.codefork.refine.resources.VIAFNameType; |
package com.codefork.refine;
/**
* Different types of names. Note that this is for the application's internal
* use; see VIAFNameType (and the asVIAFNameType() method in this enum) for a
* class used to format data sent to VIAF.
*/
public enum NameType {
Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// can't find better freebase ids for these two
Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
// ids are from freebase identifier ns
private final String id;
private final String displayName;
private final String viafCode;
private final String cqlString;
NameType(String id, String displayName, String viafCode, String cqlString) {
this.id = id;
this.displayName = displayName;
this.viafCode = viafCode;
this.cqlString = cqlString;
}
public String getId() {
return id;
}
public String getDisplayName() {
return displayName;
}
public String getViafCode() {
return viafCode;
}
public String getCqlString() {
return cqlString;
}
| // Path: src/main/java/com/codefork/refine/resources/VIAFNameType.java
// public class VIAFNameType {
//
// private String id;
// private String name;
//
// public VIAFNameType(String id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public boolean equals(Object obj) {
// if(obj instanceof VIAFNameType) {
// VIAFNameType obj2 = (VIAFNameType) obj;
// return obj2.getId().equals(getId())
// && obj2.getName().equals(getName());
// }
// return false;
// }
// }
// Path: src/main/java/com/codefork/refine/NameType.java
import com.codefork.refine.resources.VIAFNameType;
package com.codefork.refine;
/**
* Different types of names. Note that this is for the application's internal
* use; see VIAFNameType (and the asVIAFNameType() method in this enum) for a
* class used to format data sent to VIAF.
*/
public enum NameType {
Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// can't find better freebase ids for these two
Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
// ids are from freebase identifier ns
private final String id;
private final String displayName;
private final String viafCode;
private final String cqlString;
NameType(String id, String displayName, String viafCode, String cqlString) {
this.id = id;
this.displayName = displayName;
this.viafCode = viafCode;
this.cqlString = cqlString;
}
public String getId() {
return id;
}
public String getDisplayName() {
return displayName;
}
public String getViafCode() {
return viafCode;
}
public String getCqlString() {
return cqlString;
}
| public VIAFNameType asVIAFNameType() { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/resources/SourceMetaDataResponse.java | // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java
// public class NonVIAFSource extends Source {
//
// private static final Map<String, String> urls = new HashMap<String, String>();
//
// static {
// urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}");
// // B2Q = no outgoing link
// // BAV = no outgoing link
// // BIBSYS = no outgoing link
// // BNC = no outgoing link
// // BNCHL = no outgoing link
// // BNF = id in URL is different from id in "sid" field, so we disable this for now
// // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}");
// // DBC = no outgoing link
// urls.put("DNB", "http://d-nb.info/gnd/{{id}}");
// // EGAXA = no outgoing link
// urls.put("ICCU", "http://id.sbn.it/af/{{id}}");
// urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}");
// // KRNLK = no outgoing link
// // LAK = no outgoing link
// urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}");
// // LNL = no outgoing link
// // MRBNR = no outgoing link
// urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}");
// // N6I = no outgoing link
// // NKC = no outgoing link
// // NLA = no outgoing link
// // NLI = no outgoing link
// // NLP = no outgoing link
// // NLR = no outgoing link
// // NSK = no outgoing link
// // NTA = no outgoing link
// // NUKAT = no outgoing link
// // PTBNP = no outgoing link
// // RERO = no outgoing link
// urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}");
// urls.put("SUDOC", "http://www.idref.fr/{{id}}/id");
// // SWNL = no outgoing link
// urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia");
// }
//
// private String code;
//
// public NonVIAFSource(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getServiceURLTemplate() {
// String url = urls.get(code);
// if(url == null) {
// // TODO: This only works when IDs match IDs in source institution URLs,
// // which is NOT the case for several sources that don't have URL templates:
// // namely: BNC, BNF, DBC, NUKAT
// // Can't think of a way to fix this right now.
// url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code);
// }
// return url;
// }
//
// @Override
// public Result formatResult(SearchQuery query, VIAFResult viafResult) {
// // if no explicit source was specified, we should use any exact
// // match if present, otherwise the most common one
// String name = query.getSource() != null ?
// viafResult.getNameBySource(query.getSource()) :
// viafResult.getExactNameOrMostCommonName(query.getQuery());
// boolean exactMatch = name != null ? name.equals(query.getQuery()) : false;
//
// String sourceNameId = viafResult.getSourceNameId(query.getSource());
//
// // if we don't have a sourceNameId or VIAF gives it as a URL,
// // use the name ID according to VIAF instead.
// if(sourceNameId == null || sourceNameId.startsWith("http")) {
// sourceNameId = viafResult.getNameId(query.getSource());
// }
//
// // if there's STILL no source ID, we still have to return something,
// // so we return 0.
// if(sourceNameId == null) {
// sourceNameId = "0";
// }
//
// Result r = new Result(
// formatID(sourceNameId),
// name,
// viafResult.getNameType(),
// StringUtil.levenshteinDistanceRatio(name, query.getQuery()),
// exactMatch);
// return r;
// }
//
// }
| import com.codefork.refine.Config;
import com.codefork.refine.viaf.sources.NonVIAFSource; | package com.codefork.refine.resources;
/**
* Service metadata for "proxy mode": the important thing here is
* "view" key contains URL template for the non-VIAF source (for example,
* the LC website) rather than for VIAF.
*/
public class SourceMetaDataResponse extends ServiceMetaDataResponse {
private String url;
| // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java
// public class NonVIAFSource extends Source {
//
// private static final Map<String, String> urls = new HashMap<String, String>();
//
// static {
// urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}");
// // B2Q = no outgoing link
// // BAV = no outgoing link
// // BIBSYS = no outgoing link
// // BNC = no outgoing link
// // BNCHL = no outgoing link
// // BNF = id in URL is different from id in "sid" field, so we disable this for now
// // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}");
// // DBC = no outgoing link
// urls.put("DNB", "http://d-nb.info/gnd/{{id}}");
// // EGAXA = no outgoing link
// urls.put("ICCU", "http://id.sbn.it/af/{{id}}");
// urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}");
// // KRNLK = no outgoing link
// // LAK = no outgoing link
// urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}");
// // LNL = no outgoing link
// // MRBNR = no outgoing link
// urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}");
// // N6I = no outgoing link
// // NKC = no outgoing link
// // NLA = no outgoing link
// // NLI = no outgoing link
// // NLP = no outgoing link
// // NLR = no outgoing link
// // NSK = no outgoing link
// // NTA = no outgoing link
// // NUKAT = no outgoing link
// // PTBNP = no outgoing link
// // RERO = no outgoing link
// urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}");
// urls.put("SUDOC", "http://www.idref.fr/{{id}}/id");
// // SWNL = no outgoing link
// urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia");
// }
//
// private String code;
//
// public NonVIAFSource(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getServiceURLTemplate() {
// String url = urls.get(code);
// if(url == null) {
// // TODO: This only works when IDs match IDs in source institution URLs,
// // which is NOT the case for several sources that don't have URL templates:
// // namely: BNC, BNF, DBC, NUKAT
// // Can't think of a way to fix this right now.
// url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code);
// }
// return url;
// }
//
// @Override
// public Result formatResult(SearchQuery query, VIAFResult viafResult) {
// // if no explicit source was specified, we should use any exact
// // match if present, otherwise the most common one
// String name = query.getSource() != null ?
// viafResult.getNameBySource(query.getSource()) :
// viafResult.getExactNameOrMostCommonName(query.getQuery());
// boolean exactMatch = name != null ? name.equals(query.getQuery()) : false;
//
// String sourceNameId = viafResult.getSourceNameId(query.getSource());
//
// // if we don't have a sourceNameId or VIAF gives it as a URL,
// // use the name ID according to VIAF instead.
// if(sourceNameId == null || sourceNameId.startsWith("http")) {
// sourceNameId = viafResult.getNameId(query.getSource());
// }
//
// // if there's STILL no source ID, we still have to return something,
// // so we return 0.
// if(sourceNameId == null) {
// sourceNameId = "0";
// }
//
// Result r = new Result(
// formatID(sourceNameId),
// name,
// viafResult.getNameType(),
// StringUtil.levenshteinDistanceRatio(name, query.getQuery()),
// exactMatch);
// return r;
// }
//
// }
// Path: src/main/java/com/codefork/refine/resources/SourceMetaDataResponse.java
import com.codefork.refine.Config;
import com.codefork.refine.viaf.sources.NonVIAFSource;
package com.codefork.refine.resources;
/**
* Service metadata for "proxy mode": the important thing here is
* "view" key contains URL template for the non-VIAF source (for example,
* the LC website) rather than for VIAF.
*/
public class SourceMetaDataResponse extends ServiceMetaDataResponse {
private String url;
| public SourceMetaDataResponse(Config config, NonVIAFSource nonVIAFSource) { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/resources/SourceMetaDataResponse.java | // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java
// public class NonVIAFSource extends Source {
//
// private static final Map<String, String> urls = new HashMap<String, String>();
//
// static {
// urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}");
// // B2Q = no outgoing link
// // BAV = no outgoing link
// // BIBSYS = no outgoing link
// // BNC = no outgoing link
// // BNCHL = no outgoing link
// // BNF = id in URL is different from id in "sid" field, so we disable this for now
// // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}");
// // DBC = no outgoing link
// urls.put("DNB", "http://d-nb.info/gnd/{{id}}");
// // EGAXA = no outgoing link
// urls.put("ICCU", "http://id.sbn.it/af/{{id}}");
// urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}");
// // KRNLK = no outgoing link
// // LAK = no outgoing link
// urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}");
// // LNL = no outgoing link
// // MRBNR = no outgoing link
// urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}");
// // N6I = no outgoing link
// // NKC = no outgoing link
// // NLA = no outgoing link
// // NLI = no outgoing link
// // NLP = no outgoing link
// // NLR = no outgoing link
// // NSK = no outgoing link
// // NTA = no outgoing link
// // NUKAT = no outgoing link
// // PTBNP = no outgoing link
// // RERO = no outgoing link
// urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}");
// urls.put("SUDOC", "http://www.idref.fr/{{id}}/id");
// // SWNL = no outgoing link
// urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia");
// }
//
// private String code;
//
// public NonVIAFSource(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getServiceURLTemplate() {
// String url = urls.get(code);
// if(url == null) {
// // TODO: This only works when IDs match IDs in source institution URLs,
// // which is NOT the case for several sources that don't have URL templates:
// // namely: BNC, BNF, DBC, NUKAT
// // Can't think of a way to fix this right now.
// url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code);
// }
// return url;
// }
//
// @Override
// public Result formatResult(SearchQuery query, VIAFResult viafResult) {
// // if no explicit source was specified, we should use any exact
// // match if present, otherwise the most common one
// String name = query.getSource() != null ?
// viafResult.getNameBySource(query.getSource()) :
// viafResult.getExactNameOrMostCommonName(query.getQuery());
// boolean exactMatch = name != null ? name.equals(query.getQuery()) : false;
//
// String sourceNameId = viafResult.getSourceNameId(query.getSource());
//
// // if we don't have a sourceNameId or VIAF gives it as a URL,
// // use the name ID according to VIAF instead.
// if(sourceNameId == null || sourceNameId.startsWith("http")) {
// sourceNameId = viafResult.getNameId(query.getSource());
// }
//
// // if there's STILL no source ID, we still have to return something,
// // so we return 0.
// if(sourceNameId == null) {
// sourceNameId = "0";
// }
//
// Result r = new Result(
// formatID(sourceNameId),
// name,
// viafResult.getNameType(),
// StringUtil.levenshteinDistanceRatio(name, query.getQuery()),
// exactMatch);
// return r;
// }
//
// }
| import com.codefork.refine.Config;
import com.codefork.refine.viaf.sources.NonVIAFSource; | package com.codefork.refine.resources;
/**
* Service metadata for "proxy mode": the important thing here is
* "view" key contains URL template for the non-VIAF source (for example,
* the LC website) rather than for VIAF.
*/
public class SourceMetaDataResponse extends ServiceMetaDataResponse {
private String url;
| // Path: src/main/java/com/codefork/refine/Config.java
// @Service
// public class Config {
//
// public static final String DEFAULT_SERVICE_NAME = "VIAF Reconciliation Service";
// private static final String CONFIG_FILENAME = "refine_viaf.properties";
//
// private Log log = LogFactory.getLog(Config.class);
// private String serviceName = DEFAULT_SERVICE_NAME;
// private Properties properties = new Properties();
//
// public Config() {
// if(new File(CONFIG_FILENAME).exists()) {
// try {
// properties.load(new FileInputStream(CONFIG_FILENAME));
// } catch (IOException ex) {
// log.error("Error reading config file, skipping it: " + ex);
// }
// }
// setServiceName(properties.getProperty("service_name", getServiceName()));
// }
//
// public String getServiceName() {
// return serviceName;
// }
//
// public void setServiceName(String serviceName) {
// this.serviceName = serviceName;
// }
//
// public Properties getProperties() {
// return properties;
// }
// }
//
// Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java
// public class NonVIAFSource extends Source {
//
// private static final Map<String, String> urls = new HashMap<String, String>();
//
// static {
// urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}");
// // B2Q = no outgoing link
// // BAV = no outgoing link
// // BIBSYS = no outgoing link
// // BNC = no outgoing link
// // BNCHL = no outgoing link
// // BNF = id in URL is different from id in "sid" field, so we disable this for now
// // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}");
// // DBC = no outgoing link
// urls.put("DNB", "http://d-nb.info/gnd/{{id}}");
// // EGAXA = no outgoing link
// urls.put("ICCU", "http://id.sbn.it/af/{{id}}");
// urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}");
// // KRNLK = no outgoing link
// // LAK = no outgoing link
// urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}");
// // LNL = no outgoing link
// // MRBNR = no outgoing link
// urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}");
// // N6I = no outgoing link
// // NKC = no outgoing link
// // NLA = no outgoing link
// // NLI = no outgoing link
// // NLP = no outgoing link
// // NLR = no outgoing link
// // NSK = no outgoing link
// // NTA = no outgoing link
// // NUKAT = no outgoing link
// // PTBNP = no outgoing link
// // RERO = no outgoing link
// urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}");
// urls.put("SUDOC", "http://www.idref.fr/{{id}}/id");
// // SWNL = no outgoing link
// urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia");
// }
//
// private String code;
//
// public NonVIAFSource(String code) {
// this.code = code;
// }
//
// public String getCode() {
// return code;
// }
//
// public String getServiceURLTemplate() {
// String url = urls.get(code);
// if(url == null) {
// // TODO: This only works when IDs match IDs in source institution URLs,
// // which is NOT the case for several sources that don't have URL templates:
// // namely: BNC, BNF, DBC, NUKAT
// // Can't think of a way to fix this right now.
// url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code);
// }
// return url;
// }
//
// @Override
// public Result formatResult(SearchQuery query, VIAFResult viafResult) {
// // if no explicit source was specified, we should use any exact
// // match if present, otherwise the most common one
// String name = query.getSource() != null ?
// viafResult.getNameBySource(query.getSource()) :
// viafResult.getExactNameOrMostCommonName(query.getQuery());
// boolean exactMatch = name != null ? name.equals(query.getQuery()) : false;
//
// String sourceNameId = viafResult.getSourceNameId(query.getSource());
//
// // if we don't have a sourceNameId or VIAF gives it as a URL,
// // use the name ID according to VIAF instead.
// if(sourceNameId == null || sourceNameId.startsWith("http")) {
// sourceNameId = viafResult.getNameId(query.getSource());
// }
//
// // if there's STILL no source ID, we still have to return something,
// // so we return 0.
// if(sourceNameId == null) {
// sourceNameId = "0";
// }
//
// Result r = new Result(
// formatID(sourceNameId),
// name,
// viafResult.getNameType(),
// StringUtil.levenshteinDistanceRatio(name, query.getQuery()),
// exactMatch);
// return r;
// }
//
// }
// Path: src/main/java/com/codefork/refine/resources/SourceMetaDataResponse.java
import com.codefork.refine.Config;
import com.codefork.refine.viaf.sources.NonVIAFSource;
package com.codefork.refine.resources;
/**
* Service metadata for "proxy mode": the important thing here is
* "view" key contains URL template for the non-VIAF source (for example,
* the LC website) rather than for VIAF.
*/
public class SourceMetaDataResponse extends ServiceMetaDataResponse {
private String url;
| public SourceMetaDataResponse(Config config, NonVIAFSource nonVIAFSource) { |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/viaf/VIAFResult.java | // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
| import com.codefork.refine.NameType;
import java.util.ArrayList;
import java.util.List; | package com.codefork.refine.viaf;
/**
* The VIAFParser extracts relevant data from the VIAF XML into
* VIAFResult instances.
*
* This is an "intermediate" data structure which needs to get
* translated into the final format for OpenRefine to consume.
*/
public class VIAFResult {
private String viafId; | // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/com/codefork/refine/viaf/VIAFResult.java
import com.codefork.refine.NameType;
import java.util.ArrayList;
import java.util.List;
package com.codefork.refine.viaf;
/**
* The VIAFParser extracts relevant data from the VIAF XML into
* VIAFResult instances.
*
* This is an "intermediate" data structure which needs to get
* translated into the final format for OpenRefine to consume.
*/
public class VIAFResult {
private String viafId; | private NameType nameType; |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/CacheManager.java | // Path: src/main/java/com/codefork/refine/resources/Result.java
// public class Result {
//
// private String id;
// private String name;
//
// /**
// * It's weird that this is a list but that's what OpenRefine expects.
// * A VIAF result only ever has one type, but maybe other reconciliation
// * services return multiple types for a name?
// */
// private List<VIAFNameType> type;
// private double score;
// private boolean match;
//
// public Result(String id, String name, NameType nameType, double score, boolean match) {
// this.id = id;
// this.name = name;
// this.type = new ArrayList<VIAFNameType>();
// this.type.add(nameType.asVIAFNameType());
// this.score = score;
// this.match = match;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<VIAFNameType> getType() {
// return type;
// }
//
// public void setType(List<VIAFNameType> resultType) {
// this.type = resultType;
// }
//
// public double getScore() {
// return score;
// }
//
// public void setScore(double score) {
// this.score = score;
// }
//
// public boolean isMatch() {
// return match;
// }
//
// public void setMatch(boolean match) {
// this.match = match;
// }
//
// }
| import com.codefork.refine.resources.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.List; | package com.codefork.refine;
/**
* Takes care of the Cache, including the thread that expires it periodically.
* We need this because the Cache object gets replaced when it expires,
* so there needs to be this intermediate object for synchronizing access
* to the Cache object.
*/
public class CacheManager {
Log log = LogFactory.getLog(CacheManager.class);
| // Path: src/main/java/com/codefork/refine/resources/Result.java
// public class Result {
//
// private String id;
// private String name;
//
// /**
// * It's weird that this is a list but that's what OpenRefine expects.
// * A VIAF result only ever has one type, but maybe other reconciliation
// * services return multiple types for a name?
// */
// private List<VIAFNameType> type;
// private double score;
// private boolean match;
//
// public Result(String id, String name, NameType nameType, double score, boolean match) {
// this.id = id;
// this.name = name;
// this.type = new ArrayList<VIAFNameType>();
// this.type.add(nameType.asVIAFNameType());
// this.score = score;
// this.match = match;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<VIAFNameType> getType() {
// return type;
// }
//
// public void setType(List<VIAFNameType> resultType) {
// this.type = resultType;
// }
//
// public double getScore() {
// return score;
// }
//
// public void setScore(double score) {
// this.score = score;
// }
//
// public boolean isMatch() {
// return match;
// }
//
// public void setMatch(boolean match) {
// this.match = match;
// }
//
// }
// Path: src/main/java/com/codefork/refine/CacheManager.java
import com.codefork.refine.resources.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.List;
package com.codefork.refine;
/**
* Takes care of the Cache, including the thread that expires it periodically.
* We need this because the Cache object gets replaced when it expires,
* so there needs to be this intermediate object for synchronizing access
* to the Cache object.
*/
public class CacheManager {
Log log = LogFactory.getLog(CacheManager.class);
| private Cache<String, List<Result>> cache = new Cache<String, List<Result>>(); |
codeforkjeff/refine_viaf | src/test/java/com/codefork/refine/viaf/StringUtilTest.java | // Path: src/main/java/com/codefork/refine/StringUtil.java
// public class StringUtil {
//
// /**
// * Shamelessly copied from this website with only a tiny modification:
// * https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
// */
// public static int levenshteinDistance (CharSequence lhs, CharSequence rhs) {
// // if strings are the same, dist is 0
// if (lhs.equals(rhs)) {
// return 0;
// }
//
// int len0 = lhs.length() + 1;
// int len1 = rhs.length() + 1;
//
// // the array of distances
// int[] cost = new int[len0];
// int[] newcost = new int[len0];
//
// // initial cost of skipping prefix in String s0
// for (int i = 0; i < len0; i++) cost[i] = i;
//
// // dynamically computing the array of distances
//
// // transformation cost for each letter in s1
// for (int j = 1; j < len1; j++) {
// // initial cost of skipping prefix in String s1
// newcost[0] = j;
//
// // transformation cost for each letter in s0
// for(int i = 1; i < len0; i++) {
// // matching current letters in both strings
// int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1;
//
// // computing cost for each transformation
// int cost_replace = cost[i - 1] + match;
// int cost_insert = cost[i] + 1;
// int cost_delete = newcost[i - 1] + 1;
//
// // keep minimum cost
// newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace);
// }
//
// // swap cost/newcost arrays
// int[] swap = cost; cost = newcost; newcost = swap;
// }
//
// // the distance is the cost for transforming all letters in both strings
// return cost[len0 - 1];
// }
//
// /**
// * Returns string similarity as a ratio. This is calculated as a ratio of
// * levenshstein distance to max possible distance (which is the length of
// * the longer string). The more dissimilar the strings are, the lower
// * the value returned. Identical strings return 1.0.
// * @param lhs
// * @param rhs
// * @return
// */
// public static double levenshteinDistanceRatio(CharSequence lhs, CharSequence rhs) {
// int maxDist = lhs.length();
// if (rhs.length() > maxDist) {
// maxDist = rhs.length();
// }
// if (maxDist == 0) {
// return 1;
// }
// return (maxDist - Double.valueOf(levenshteinDistance(lhs, rhs))) / Double.valueOf(maxDist);
// }
//
// /**
// * consumes an InputStream into a String
// * @param is
// * @param bufferSize
// * @return
// */
// public static String inputStreamToString(final InputStream is, final int bufferSize) {
// final char[] buffer = new char[bufferSize];
// final StringBuilder out = new StringBuilder();
// try {
// Reader in = new InputStreamReader(is, "UTF-8");
// for (;;) {
// int rsz = in.read(buffer, 0, buffer.length);
// if (rsz < 0)
// break;
// out.append(buffer, 0, rsz);
// }
// }
// catch (UnsupportedEncodingException ex) {
// }
// catch (IOException ex) {
// }
// return out.toString();
// }
//
// }
| import com.codefork.refine.StringUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package com.codefork.refine.viaf;
public class StringUtilTest {
@Test
public void testLevenshteinDistance() {
String s = "this is a test sentence"; | // Path: src/main/java/com/codefork/refine/StringUtil.java
// public class StringUtil {
//
// /**
// * Shamelessly copied from this website with only a tiny modification:
// * https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
// */
// public static int levenshteinDistance (CharSequence lhs, CharSequence rhs) {
// // if strings are the same, dist is 0
// if (lhs.equals(rhs)) {
// return 0;
// }
//
// int len0 = lhs.length() + 1;
// int len1 = rhs.length() + 1;
//
// // the array of distances
// int[] cost = new int[len0];
// int[] newcost = new int[len0];
//
// // initial cost of skipping prefix in String s0
// for (int i = 0; i < len0; i++) cost[i] = i;
//
// // dynamically computing the array of distances
//
// // transformation cost for each letter in s1
// for (int j = 1; j < len1; j++) {
// // initial cost of skipping prefix in String s1
// newcost[0] = j;
//
// // transformation cost for each letter in s0
// for(int i = 1; i < len0; i++) {
// // matching current letters in both strings
// int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1;
//
// // computing cost for each transformation
// int cost_replace = cost[i - 1] + match;
// int cost_insert = cost[i] + 1;
// int cost_delete = newcost[i - 1] + 1;
//
// // keep minimum cost
// newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace);
// }
//
// // swap cost/newcost arrays
// int[] swap = cost; cost = newcost; newcost = swap;
// }
//
// // the distance is the cost for transforming all letters in both strings
// return cost[len0 - 1];
// }
//
// /**
// * Returns string similarity as a ratio. This is calculated as a ratio of
// * levenshstein distance to max possible distance (which is the length of
// * the longer string). The more dissimilar the strings are, the lower
// * the value returned. Identical strings return 1.0.
// * @param lhs
// * @param rhs
// * @return
// */
// public static double levenshteinDistanceRatio(CharSequence lhs, CharSequence rhs) {
// int maxDist = lhs.length();
// if (rhs.length() > maxDist) {
// maxDist = rhs.length();
// }
// if (maxDist == 0) {
// return 1;
// }
// return (maxDist - Double.valueOf(levenshteinDistance(lhs, rhs))) / Double.valueOf(maxDist);
// }
//
// /**
// * consumes an InputStream into a String
// * @param is
// * @param bufferSize
// * @return
// */
// public static String inputStreamToString(final InputStream is, final int bufferSize) {
// final char[] buffer = new char[bufferSize];
// final StringBuilder out = new StringBuilder();
// try {
// Reader in = new InputStreamReader(is, "UTF-8");
// for (;;) {
// int rsz = in.read(buffer, 0, buffer.length);
// if (rsz < 0)
// break;
// out.append(buffer, 0, rsz);
// }
// }
// catch (UnsupportedEncodingException ex) {
// }
// catch (IOException ex) {
// }
// return out.toString();
// }
//
// }
// Path: src/test/java/com/codefork/refine/viaf/StringUtilTest.java
import com.codefork.refine.StringUtil;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package com.codefork.refine.viaf;
public class StringUtilTest {
@Test
public void testLevenshteinDistance() {
String s = "this is a test sentence"; | assertEquals(0, StringUtil.levenshteinDistance(s, "this is a test sentence")); |
codeforkjeff/refine_viaf | src/test/java/com/codefork/refine/viaf/ThreadPoolTest.java | // Path: src/main/java/com/codefork/refine/ThreadPool.java
// public class ThreadPool {
//
// /**
// * NOTE: VIAF seems to have a limit of 6 simultaneous
// * requests. To be conservative, we default to 4 for
// * the entire app.
// */
// public static final int INITIAL_POOL_SIZE = 4;
//
// // shrink rapidly, but grow slowly
// private long waitPeriodBeforeShrinkingMs = 30000; // 30s
// private long waitPeriodBeforeGrowingMs = 600000; // 10 mins
// private long waitPeriodBeforeResetMs = 3600000; // 1 hour
//
// private Log log = LogFactory.getLog(ThreadPool.class);
//
// private ThreadPoolExecutor executor;
// private long lastTimePoolAdjusted = 0;
//
// public ThreadPool() {
// // TODO: make thread pool size configurable
// log.info("Starting thread pool, size = " + INITIAL_POOL_SIZE);
// executor = new ThreadPoolExecutor(INITIAL_POOL_SIZE, INITIAL_POOL_SIZE, 0, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>());
// }
//
// public ThreadPool(long waitPeriodBeforeShrinkingMs,
// long waitPeriodBeforeGrowingMs,
// long waitPeriodBeforeResetMs) {
// this();
// this.waitPeriodBeforeShrinkingMs = waitPeriodBeforeShrinkingMs;
// this.waitPeriodBeforeGrowingMs = waitPeriodBeforeGrowingMs;
// this.waitPeriodBeforeResetMs = waitPeriodBeforeResetMs;
// }
//
// /**
// * Submit a task to the pool, returning a Future immediately.
// * Also tries to grow the pool, if necessary.
// * @param task
// * @return
// */
// public Future<SearchResult> submit(SearchTask task) {
// if(lastTimePoolAdjusted != 0) {
// grow();
// long now = System.currentTimeMillis();
// if(now - lastTimePoolAdjusted > waitPeriodBeforeResetMs) {
// // reset this var, to prevent submit() from trying to grow back
// lastTimePoolAdjusted = 0;
// }
// }
// return executor.submit(task);
// }
//
// /**
// * @return current size of the thread pool
// */
// public int getPoolSize() {
// return executor.getCorePoolSize();
// }
//
// private void setPoolSize(int newSize) {
// executor.setCorePoolSize(newSize);
// executor.setMaximumPoolSize(newSize);
// }
//
// /**
// * Shrink the size of the pool, if we can.
// */
// public synchronized void shrink() {
// int size = getPoolSize();
// if(size > 1) {
// long now = System.currentTimeMillis();
// // we need a bit of time for the last operation to take effect
// // before we try to shrink again
// if(now - lastTimePoolAdjusted > waitPeriodBeforeShrinkingMs) {
// int newSize = size - 1;
// log.info("Shrinking pool, new size = " + newSize);
// setPoolSize(newSize);
// lastTimePoolAdjusted = now;
// }
// }
// }
//
// /**
// * Grow the size of the pool back up to the initial size, if we can.
// */
// public synchronized void grow() {
// int size = getPoolSize();
// if(size < INITIAL_POOL_SIZE) {
// long now = System.currentTimeMillis();
// // grow slowly
// if(now - lastTimePoolAdjusted > waitPeriodBeforeGrowingMs) {
// int newSize = size + 1;
// log.info("Growing pool, new size = " + newSize);
// setPoolSize(newSize);
// lastTimePoolAdjusted = now;
// }
// }
// }
//
// public void shutdown() {
// log.info("Shutting down thread pool");
// executor.shutdown();
// try {
// executor.awaitTermination(30, TimeUnit.SECONDS);
// } catch(InterruptedException e) {
// log.error("Executor was interrupted while awaiting termination: " + e);
// }
// }
//
// }
| import com.codefork.refine.ThreadPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | package com.codefork.refine.viaf;
public class ThreadPoolTest {
@Test
public void testShrinkAndGrow() throws Exception {
// test shrink and grow, using much smaller wait period times
long waitPeriodBeforeShrinkingMs = 1000;
long waitPeriodBeforeGrowingMs = 2000;
long waitPeriodBeforeResetMs = 3600000; // 1 hour
| // Path: src/main/java/com/codefork/refine/ThreadPool.java
// public class ThreadPool {
//
// /**
// * NOTE: VIAF seems to have a limit of 6 simultaneous
// * requests. To be conservative, we default to 4 for
// * the entire app.
// */
// public static final int INITIAL_POOL_SIZE = 4;
//
// // shrink rapidly, but grow slowly
// private long waitPeriodBeforeShrinkingMs = 30000; // 30s
// private long waitPeriodBeforeGrowingMs = 600000; // 10 mins
// private long waitPeriodBeforeResetMs = 3600000; // 1 hour
//
// private Log log = LogFactory.getLog(ThreadPool.class);
//
// private ThreadPoolExecutor executor;
// private long lastTimePoolAdjusted = 0;
//
// public ThreadPool() {
// // TODO: make thread pool size configurable
// log.info("Starting thread pool, size = " + INITIAL_POOL_SIZE);
// executor = new ThreadPoolExecutor(INITIAL_POOL_SIZE, INITIAL_POOL_SIZE, 0, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>());
// }
//
// public ThreadPool(long waitPeriodBeforeShrinkingMs,
// long waitPeriodBeforeGrowingMs,
// long waitPeriodBeforeResetMs) {
// this();
// this.waitPeriodBeforeShrinkingMs = waitPeriodBeforeShrinkingMs;
// this.waitPeriodBeforeGrowingMs = waitPeriodBeforeGrowingMs;
// this.waitPeriodBeforeResetMs = waitPeriodBeforeResetMs;
// }
//
// /**
// * Submit a task to the pool, returning a Future immediately.
// * Also tries to grow the pool, if necessary.
// * @param task
// * @return
// */
// public Future<SearchResult> submit(SearchTask task) {
// if(lastTimePoolAdjusted != 0) {
// grow();
// long now = System.currentTimeMillis();
// if(now - lastTimePoolAdjusted > waitPeriodBeforeResetMs) {
// // reset this var, to prevent submit() from trying to grow back
// lastTimePoolAdjusted = 0;
// }
// }
// return executor.submit(task);
// }
//
// /**
// * @return current size of the thread pool
// */
// public int getPoolSize() {
// return executor.getCorePoolSize();
// }
//
// private void setPoolSize(int newSize) {
// executor.setCorePoolSize(newSize);
// executor.setMaximumPoolSize(newSize);
// }
//
// /**
// * Shrink the size of the pool, if we can.
// */
// public synchronized void shrink() {
// int size = getPoolSize();
// if(size > 1) {
// long now = System.currentTimeMillis();
// // we need a bit of time for the last operation to take effect
// // before we try to shrink again
// if(now - lastTimePoolAdjusted > waitPeriodBeforeShrinkingMs) {
// int newSize = size - 1;
// log.info("Shrinking pool, new size = " + newSize);
// setPoolSize(newSize);
// lastTimePoolAdjusted = now;
// }
// }
// }
//
// /**
// * Grow the size of the pool back up to the initial size, if we can.
// */
// public synchronized void grow() {
// int size = getPoolSize();
// if(size < INITIAL_POOL_SIZE) {
// long now = System.currentTimeMillis();
// // grow slowly
// if(now - lastTimePoolAdjusted > waitPeriodBeforeGrowingMs) {
// int newSize = size + 1;
// log.info("Growing pool, new size = " + newSize);
// setPoolSize(newSize);
// lastTimePoolAdjusted = now;
// }
// }
// }
//
// public void shutdown() {
// log.info("Shutting down thread pool");
// executor.shutdown();
// try {
// executor.awaitTermination(30, TimeUnit.SECONDS);
// } catch(InterruptedException e) {
// log.error("Executor was interrupted while awaiting termination: " + e);
// }
// }
//
// }
// Path: src/test/java/com/codefork/refine/viaf/ThreadPoolTest.java
import com.codefork.refine.ThreadPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
package com.codefork.refine.viaf;
public class ThreadPoolTest {
@Test
public void testShrinkAndGrow() throws Exception {
// test shrink and grow, using much smaller wait period times
long waitPeriodBeforeShrinkingMs = 1000;
long waitPeriodBeforeGrowingMs = 2000;
long waitPeriodBeforeResetMs = 3600000; // 1 hour
| ThreadPool pool = new ThreadPool(waitPeriodBeforeShrinkingMs, waitPeriodBeforeGrowingMs, waitPeriodBeforeResetMs); |
codeforkjeff/refine_viaf | src/main/java/com/codefork/refine/viaf/VIAFParser.java | // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
| import com.codefork.refine.NameType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack; |
StartElementHandler captureHandler = new StartElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName, Attributes attributes) {
parser.captureChars = true;
}
};
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/nameType",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/viafID",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/text",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/sources/s",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/sources/sid",
captureHandler);
endElementHandlers.put("searchRetrieveResponse/records/record",
new EndElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName) {
parser.associateSourceIds();
parser.results.add(parser.result);
parser.result = null;
}
});
endElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/nameType",
new EndElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName) { | // Path: src/main/java/com/codefork/refine/NameType.java
// public enum NameType {
// Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""),
// Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""),
// Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""),
// // can't find better freebase ids for these two
// Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""),
// Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\"");
//
// // ids are from freebase identifier ns
// private final String id;
// private final String displayName;
// private final String viafCode;
// private final String cqlString;
//
// NameType(String id, String displayName, String viafCode, String cqlString) {
// this.id = id;
// this.displayName = displayName;
// this.viafCode = viafCode;
// this.cqlString = cqlString;
// }
//
// public String getId() {
// return id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public String getViafCode() {
// return viafCode;
// }
//
// public String getCqlString() {
// return cqlString;
// }
//
// public VIAFNameType asVIAFNameType() {
// return new VIAFNameType(getId(), getDisplayName());
// }
//
// public static NameType getByViafCode(String viafCodeArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.viafCode.equals(viafCodeArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// public static NameType getById(String idArg) {
// for(NameType nameType: NameType.values()) {
// if(nameType.id.equals(idArg)) {
// return nameType;
// }
// }
// return null;
// }
//
// }
// Path: src/main/java/com/codefork/refine/viaf/VIAFParser.java
import com.codefork.refine.NameType;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
StartElementHandler captureHandler = new StartElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName, Attributes attributes) {
parser.captureChars = true;
}
};
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/nameType",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/viafID",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/text",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/sources/s",
captureHandler);
startElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/mainHeadings/data/sources/sid",
captureHandler);
endElementHandlers.put("searchRetrieveResponse/records/record",
new EndElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName) {
parser.associateSourceIds();
parser.results.add(parser.result);
parser.result = null;
}
});
endElementHandlers.put("searchRetrieveResponse/records/record/recordData/VIAFCluster/nameType",
new EndElementHandler() {
public void handle(VIAFParser parser, String uri, String localName, String qName) { | parser.result.setNameType(NameType.getByViafCode(parser.buf.toString())) ; |
AdamBien/porcupine | porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/DefaulThreadPoolExecutorTest.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
//
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/control/ManagedThreadFactoryExposerMock.java
// public class ManagedThreadFactoryExposerMock {
//
// @Produces
// public ManagedThreadFactory expose() {
// return (r) -> newThread(r);
// }
//
// Thread newThread(Runnable r) {
// Thread thread = new Thread(r, "-ManagedThreadFactoryExposerMock-");
// thread.setDaemon(false);
// return thread;
// }
// }
| import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import com.airhacks.porcupine.execution.control.ManagedThreadFactoryExposerMock;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class DefaulThreadPoolExecutorTest {
ExecutorServiceExposer cut;
@Before
public void init() {
this.cut = new ExecutorServiceExposer(); | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
//
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/control/ManagedThreadFactoryExposerMock.java
// public class ManagedThreadFactoryExposerMock {
//
// @Produces
// public ManagedThreadFactory expose() {
// return (r) -> newThread(r);
// }
//
// Thread newThread(Runnable r) {
// Thread thread = new Thread(r, "-ManagedThreadFactoryExposerMock-");
// thread.setDaemon(false);
// return thread;
// }
// }
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/DefaulThreadPoolExecutorTest.java
import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import com.airhacks.porcupine.execution.control.ManagedThreadFactoryExposerMock;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class DefaulThreadPoolExecutorTest {
ExecutorServiceExposer cut;
@Before
public void init() {
this.cut = new ExecutorServiceExposer(); | this.cut.threadFactory = new ManagedThreadFactoryExposerMock().expose(); |
AdamBien/porcupine | porcupine-sample/src/main/java/com/airhacks/threading/statistics/boundary/RejectionsNotifier.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Rejection.java
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Rejection {
//
// private Statistics statistics;
// private String taskClass;
//
// public Rejection(Statistics statistics, String taskClass) {
// this.statistics = statistics;
// this.taskClass = taskClass;
// }
//
// public Rejection() {
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public String getTaskClass() {
// return taskClass;
// }
//
// @Override
// public String toString() {
// return "Rejection{" + "statistics=" + statistics + ", taskClass=" + taskClass + '}';
// }
// }
| import com.airhacks.porcupine.execution.entity.Rejection;
import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint; | package com.airhacks.threading.statistics.boundary;
/**
*
* @author airhacks.com
*/
@Singleton
@ServerEndpoint("/rejections")
public class RejectionsNotifier {
private Session session;
@OnOpen
public void open(Session session) {
this.session = session;
}
@OnClose
public void close() {
this.session = null;
}
| // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Rejection.java
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Rejection {
//
// private Statistics statistics;
// private String taskClass;
//
// public Rejection(Statistics statistics, String taskClass) {
// this.statistics = statistics;
// this.taskClass = taskClass;
// }
//
// public Rejection() {
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public String getTaskClass() {
// return taskClass;
// }
//
// @Override
// public String toString() {
// return "Rejection{" + "statistics=" + statistics + ", taskClass=" + taskClass + '}';
// }
// }
// Path: porcupine-sample/src/main/java/com/airhacks/threading/statistics/boundary/RejectionsNotifier.java
import com.airhacks.porcupine.execution.entity.Rejection;
import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
package com.airhacks.threading.statistics.boundary;
/**
*
* @author airhacks.com
*/
@Singleton
@ServerEndpoint("/rejections")
public class RejectionsNotifier {
private Session session;
@OnOpen
public void open(Session session) {
this.session = session;
}
@OnClose
public void close() {
this.session = null;
}
| public void onNewRejection(@Observes Rejection rejectedTask) { |
AdamBien/porcupine | porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/CustomThreadFactoryExposerTest.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ThreadFactoryExposer.java
// public class ThreadFactoryExposer {
//
// @Resource
// ManagedThreadFactory threadFactory;
//
// @Produces
// public ThreadFactory expose() {
// return this.threadFactory;
// }
// }
| import com.airhacks.porcupine.execution.control.ThreadFactoryExposer;
import java.io.File;
import java.util.concurrent.ThreadFactory;
import javax.inject.Inject;
import static org.hamcrest.CoreMatchers.is;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
@RunWith(Arquillian.class)
public class CustomThreadFactoryExposerTest {
@Inject
ThreadFactory custom;
@Deployment
public static Archive create() {
return ShrinkWrap.create(WebArchive.class).
addClasses(CustomThreadFactoryExposer.class, | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ThreadFactoryExposer.java
// public class ThreadFactoryExposer {
//
// @Resource
// ManagedThreadFactory threadFactory;
//
// @Produces
// public ThreadFactory expose() {
// return this.threadFactory;
// }
// }
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/CustomThreadFactoryExposerTest.java
import com.airhacks.porcupine.execution.control.ThreadFactoryExposer;
import java.io.File;
import java.util.concurrent.ThreadFactory;
import javax.inject.Inject;
import static org.hamcrest.CoreMatchers.is;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
@RunWith(Arquillian.class)
public class CustomThreadFactoryExposerTest {
@Inject
ThreadFactory custom;
@Deployment
public static Archive create() {
return ShrinkWrap.create(WebArchive.class).
addClasses(CustomThreadFactoryExposer.class, | ThreadFactoryExposer.class). |
AdamBien/porcupine | porcupine-sample/src/main/java/com/airhacks/threading/statistics/boundary/StatisticsResource.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
| import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package com.airhacks.threading.statistics.boundary;
/**
*
* @author airhacks.com
*/
@Path("statistics")
@RequestScoped
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class StatisticsResource {
@Inject | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
// Path: porcupine-sample/src/main/java/com/airhacks/threading/statistics/boundary/StatisticsResource.java
import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package com.airhacks.threading.statistics.boundary;
/**
*
* @author airhacks.com
*/
@Path("statistics")
@RequestScoped
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class StatisticsResource {
@Inject | Instance<List<Statistics>> statistics; |
AdamBien/porcupine | porcupine-spy/src/main/java/com/airhacks/porcupine/interceptors/HttpHeaderStatisticInjector.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
| import com.airhacks.porcupine.execution.entity.Statistics;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.interceptors;
/**
*
* @author airhacks.com
*/
@Provider
public class HttpHeaderStatisticInjector implements WriterInterceptor {
@Inject | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
// Path: porcupine-spy/src/main/java/com/airhacks/porcupine/interceptors/HttpHeaderStatisticInjector.java
import com.airhacks.porcupine.execution.entity.Statistics;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.interceptors;
/**
*
* @author airhacks.com
*/
@Provider
public class HttpHeaderStatisticInjector implements WriterInterceptor {
@Inject | Instance<List<Statistics>> statistics; |
AdamBien/porcupine | porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/InstrumentedThreadPoolExecutor.java
// public class InstrumentedThreadPoolExecutor extends ThreadPoolExecutor {
//
// private int minRemainingQueueCapacity;
//
// public InstrumentedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
// super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
// this.minRemainingQueueCapacity = workQueue.remainingCapacity();
// }
//
// @Override
// protected void afterExecute(Runnable r, Throwable t) {
// super.afterExecute(r, t);
// }
//
// @Override
// protected void beforeExecute(Thread t, Runnable r) {
// super.beforeExecute(t, r);
// int current = super.getQueue().remainingCapacity();
// this.minRemainingQueueCapacity = min(this.minRemainingQueueCapacity, current);
// }
//
// public int getMinRemainingQueueCapacity() {
// return minRemainingQueueCapacity;
// }
// }
| import com.airhacks.porcupine.execution.control.InstrumentedThreadPoolExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.entity;
/**
*
* An internal class -- don't use it in your application.
*
* @author airhacks.com
*/
public class Pipeline {
private final String pipelineName; | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/InstrumentedThreadPoolExecutor.java
// public class InstrumentedThreadPoolExecutor extends ThreadPoolExecutor {
//
// private int minRemainingQueueCapacity;
//
// public InstrumentedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
// super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
// this.minRemainingQueueCapacity = workQueue.remainingCapacity();
// }
//
// @Override
// protected void afterExecute(Runnable r, Throwable t) {
// super.afterExecute(r, t);
// }
//
// @Override
// protected void beforeExecute(Thread t, Runnable r) {
// super.beforeExecute(t, r);
// int current = super.getQueue().remainingCapacity();
// this.minRemainingQueueCapacity = min(this.minRemainingQueueCapacity, current);
// }
//
// public int getMinRemainingQueueCapacity() {
// return minRemainingQueueCapacity;
// }
// }
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java
import com.airhacks.porcupine.execution.control.InstrumentedThreadPoolExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.entity;
/**
*
* An internal class -- don't use it in your application.
*
* @author airhacks.com
*/
public class Pipeline {
private final String pipelineName; | private final InstrumentedThreadPoolExecutor tpe; |
AdamBien/porcupine | porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/OverloadedConfiguration.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
| import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import javax.enterprise.inject.Specializes; | /*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
@Specializes
public class OverloadedConfiguration extends ExecutorConfigurator {
@Override | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/boundary/OverloadedConfiguration.java
import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import javax.enterprise.inject.Specializes;
/*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
@Specializes
public class OverloadedConfiguration extends ExecutorConfigurator {
@Override | public ExecutorConfiguration forPipeline(String name) { |
AdamBien/porcupine | porcupine-spy/src/test/java/com/airhacks/porcupine/interceptors/HttpHeaderStatisticInjectorTest.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
| import com.airhacks.porcupine.execution.entity.Statistics;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.interceptors;
/**
*
* @author airhacks.com
*/
public class HttpHeaderStatisticInjectorTest {
private HttpHeaderStatisticInjector cut;
@Before
public void init() {
this.cut = new HttpHeaderStatisticInjector();
}
@Test
public void serializeStatistics() { | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
// Path: porcupine-spy/src/test/java/com/airhacks/porcupine/interceptors/HttpHeaderStatisticInjectorTest.java
import com.airhacks.porcupine.execution.entity.Statistics;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.interceptors;
/**
*
* @author airhacks.com
*/
public class HttpHeaderStatisticInjectorTest {
private HttpHeaderStatisticInjector cut;
@Before
public void init() {
this.cut = new HttpHeaderStatisticInjector();
}
@Test
public void serializeStatistics() { | Statistics stats = new Statistics("test", 0, 1, 2, 3, 4, 5, 6, 7, 8, "duke", 9); |
AdamBien/porcupine | porcupine-sample/src/main/java/com/airhacks/threading/messages/boundary/MessagesService.java | // Path: porcupine-sample/src/main/java/com/airhacks/threading/messages/control/MessageReceiver.java
// public class MessageReceiver {
//
// public String receiveLightMessage() {
// return "Message " + new Date();
// }
//
// public String receiveHeavyMessage() {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException ex) {
// Logger.getLogger(MessageReceiver.class.getName()).log(Level.SEVERE, null, ex);
// }
// return "Message " + new Date();
// }
// }
| import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.threading.messages.control.MessageReceiver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import javax.ejb.Stateless;
import javax.inject.Inject; | package com.airhacks.threading.messages.boundary;
/**
*
* @author airhacks.com
*/
@Stateless
public class MessagesService {
@Inject
@Dedicated
ExecutorService light;
@Inject
@Dedicated
ExecutorService heavy;
@Inject | // Path: porcupine-sample/src/main/java/com/airhacks/threading/messages/control/MessageReceiver.java
// public class MessageReceiver {
//
// public String receiveLightMessage() {
// return "Message " + new Date();
// }
//
// public String receiveHeavyMessage() {
// try {
// Thread.sleep(5000);
// } catch (InterruptedException ex) {
// Logger.getLogger(MessageReceiver.class.getName()).log(Level.SEVERE, null, ex);
// }
// return "Message " + new Date();
// }
// }
// Path: porcupine-sample/src/main/java/com/airhacks/threading/messages/boundary/MessagesService.java
import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.threading.messages.control.MessageReceiver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import javax.ejb.Stateless;
import javax.inject.Inject;
package com.airhacks.threading.messages.boundary;
/**
*
* @author airhacks.com
*/
@Stateless
public class MessagesService {
@Inject
@Dedicated
ExecutorService light;
@Inject
@Dedicated
ExecutorService heavy;
@Inject | MessageReceiver fetcher; |
AdamBien/porcupine | porcupine/src/test/java/com/airhacks/porcupine/execution/control/ExecutorServiceDedicatedInjectionTarget.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
| import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.control;
/**
*
* @author airhacks.com
*/
public class ExecutorServiceDedicatedInjectionTarget {
public final static String CUSTOM_FIRST = "customFirst";
public final static String CUSTOM_SECOND = "customSecond";
@Inject
@Dedicated(CUSTOM_FIRST)
private ExecutorService first;
@Inject
@Dedicated(CUSTOM_SECOND)
private ExecutorService second;
@Inject
@Dedicated(CUSTOM_FIRST) | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/control/ExecutorServiceDedicatedInjectionTarget.java
import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.control;
/**
*
* @author airhacks.com
*/
public class ExecutorServiceDedicatedInjectionTarget {
public final static String CUSTOM_FIRST = "customFirst";
public final static String CUSTOM_SECOND = "customSecond";
@Inject
@Dedicated(CUSTOM_FIRST)
private ExecutorService first;
@Inject
@Dedicated(CUSTOM_SECOND)
private ExecutorService second;
@Inject
@Dedicated(CUSTOM_FIRST) | private Instance<Statistics> firstStatistics; |
AdamBien/porcupine | porcupine-sample/src/main/java/com/airhacks/threading/messages/control/CustomExecutorConfigurator.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
| import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import javax.enterprise.inject.Specializes; | package com.airhacks.threading.messages.control;
/**
*
* @author airhacks.com
*/
@Specializes
public class CustomExecutorConfigurator extends ExecutorConfigurator {
@Override | // Path: porcupine/src/main/java/com/airhacks/porcupine/configuration/control/ExecutorConfigurator.java
// public class ExecutorConfigurator {
//
// /**
// *
// * @param name the name used within the {@link Dedicated} qualifier.
// * @return a default configuration, unless overridden
// */
// public ExecutorConfiguration forPipeline(String name) {
// return defaultConfigurator();
// }
//
// /**
// *
// * @return the default configuration for all injected
// * {@link ExecutorService} instances (unless overridden and specialized
// * {@link Specializes})
// */
// public ExecutorConfiguration defaultConfigurator() {
// return ExecutorConfiguration.defaultConfiguration();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/ExecutorConfiguration.java
// public class ExecutorConfiguration {
//
// private int corePoolSize;
// private int keepAliveTime;
// private int maxPoolSize;
// private int queueCapacity;
// private RejectedExecutionHandler rejectedExecutionHandler;
//
// private ExecutorConfiguration() {
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// this.corePoolSize = availableProcessors;
// this.maxPoolSize = availableProcessors * 2;
// this.keepAliveTime = 1;
// this.queueCapacity = 100;
//
// }
//
// public final static class Builder {
//
// ExecutorConfiguration configuration = new ExecutorConfiguration();
//
// public Builder corePoolSize(int corePoolSize) {
// configuration.corePoolSize = corePoolSize;
// return this;
// }
//
// public Builder keepAliveTime(int keepAliveTime) {
// configuration.keepAliveTime = keepAliveTime;
// return this;
// }
//
// public Builder maxPoolSize(int maxPoolSize) {
// configuration.maxPoolSize = maxPoolSize;
// return this;
// }
//
// public Builder queueCapacity(int queueCapacity) {
// configuration.queueCapacity = queueCapacity;
// return this;
// }
//
// public Builder abortPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
// return this;
// }
//
// public Builder callerRunsPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
// return this;
// }
//
// public Builder discardPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardPolicy();
// return this;
// }
//
// public Builder discardOldestPolicy() {
// configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
// return this;
// }
//
// public Builder customRejectedExecutionHandler(RejectedExecutionHandler reh) {
// configuration.rejectedExecutionHandler = reh;
// return this;
// }
//
// void validateConfiguration() {
// if (this.configuration.keepAliveTime < 0) {
// throw new IllegalStateException("keepAliveTime is: " + this.configuration.keepAliveTime + " but should be > 0");
// }
//
// if (this.configuration.queueCapacity < 0) {
// throw new IllegalStateException("queueCapacity is: " + this.configuration.queueCapacity + " but should be > 0");
// }
// if (this.configuration.corePoolSize > this.configuration.maxPoolSize) {
// throw new IllegalStateException("corePoolSize(" + this.configuration.corePoolSize + ") is larger than maxPoolSize(" + this.configuration.maxPoolSize + ")");
// }
// }
//
// public ExecutorConfiguration build() {
// validateConfiguration();
// return configuration;
//
// }
// }
//
// /**
// *
// * @return default configuration. corePoolSize is the amount of cores, the
// * maxPoolSize twice the amount of cores, keepAliveTime is one second and
// * the queueCapacity is 100.
// */
// public static final ExecutorConfiguration defaultConfiguration() {
// return new ExecutorConfiguration();
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// public int getKeepAliveTime() {
// return keepAliveTime;
// }
//
// public int getMaxPoolSize() {
// return maxPoolSize;
// }
//
// public int getQueueCapacity() {
// return queueCapacity;
// }
//
// public RejectedExecutionHandler getRejectedExecutionHandler() {
// return rejectedExecutionHandler;
// }
//
// }
// Path: porcupine-sample/src/main/java/com/airhacks/threading/messages/control/CustomExecutorConfigurator.java
import com.airhacks.porcupine.configuration.control.ExecutorConfigurator;
import com.airhacks.porcupine.execution.control.ExecutorConfiguration;
import javax.enterprise.inject.Specializes;
package com.airhacks.threading.messages.control;
/**
*
* @author airhacks.com
*/
@Specializes
public class CustomExecutorConfigurator extends ExecutorConfigurator {
@Override | public ExecutorConfiguration defaultConfigurator() { |
AdamBien/porcupine | porcupine/src/main/java/com/airhacks/porcupine/execution/boundary/RejectionsCounter.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/PipelineStore.java
// @ApplicationScoped
// public class PipelineStore {
//
// ConcurrentHashMap<String, Pipeline> pipelines;
//
// @PostConstruct
// public void init() {
// this.pipelines = new ConcurrentHashMap<>();
// }
//
// public Pipeline get(String name) {
// return this.pipelines.get(name);
// }
//
// public void put(String pipelineName, Pipeline pipeline) {
// this.pipelines.put(pipelineName, pipeline);
// }
//
// public Collection<Pipeline> pipelines() {
// return this.pipelines.values();
//
// }
//
// public Statistics getStatistics(String name) {
// Pipeline pipeline = this.pipelines.get(name);
// if (pipeline != null) {
// return pipeline.getStatistics();
// } else {
// return new Statistics();
// }
// }
//
// public int getNumberOfPipelines() {
// return this.pipelines.size();
// }
//
// public List<Statistics> getAllStatistics() {
// return this.pipelines.values().stream().
// map(p -> p.getStatistics()).
// collect(Collectors.toList());
// }
//
// public void clear() {
// this.pipelines.clear();
// }
//
// public Pipeline findPipeline(ThreadPoolExecutor executor) {
// return this.pipelines().stream().filter((p) -> p.manages(executor)).findFirst().orElse(null);
// }
//
// @PreDestroy
// public void shutdown() {
// this.pipelines.values().parallelStream().forEach(p -> p.shutdown());
// this.pipelines.clear();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java
// public class Pipeline {
//
// private final String pipelineName;
// private final InstrumentedThreadPoolExecutor tpe;
// private final AtomicLong rejectedTasks;
//
// public Pipeline(String pipelineName, InstrumentedThreadPoolExecutor tpe) {
// this.pipelineName = pipelineName;
// this.tpe = tpe;
// this.rejectedTasks = new AtomicLong();
// }
//
// public Statistics getStatistics() {
// int remainingQueueCapacity = this.tpe.getQueue().remainingCapacity();
// int minQueueCapacity = this.tpe.getMinRemainingQueueCapacity();
// int corePoolSize = this.tpe.getCorePoolSize();
// long completedTaskCount = this.tpe.getCompletedTaskCount();
// int activeThreadCount = this.tpe.getActiveCount();
// int largestThreadPoolSize = this.tpe.getLargestPoolSize();
// int currentThreadPoolSize = this.tpe.getPoolSize();
// long totalNumberOfTasks = this.tpe.getTaskCount();
// int maximumPoolSize = this.tpe.getMaximumPoolSize();
// RejectedExecutionHandler handler = this.tpe.getRejectedExecutionHandler();
// String rejectedExecutionHandlerName = null;
// if (handler != null) {
// rejectedExecutionHandlerName = handler.getClass().getSimpleName();
// }
// return new Statistics(this.pipelineName, remainingQueueCapacity, minQueueCapacity, completedTaskCount, activeThreadCount, corePoolSize, largestThreadPoolSize, currentThreadPoolSize, totalNumberOfTasks, maximumPoolSize, rejectedExecutionHandlerName, this.rejectedTasks.get());
//
// }
//
// public ExecutorService getExecutor() {
// return tpe;
// }
//
// public void shutdown() {
// this.tpe.shutdown();
// }
//
// public boolean manages(ThreadPoolExecutor executor) {
// return this.tpe == executor;
// }
//
// public void taskRejected() {
// this.rejectedTasks.incrementAndGet();
// }
//
// }
| import com.airhacks.porcupine.execution.control.PipelineStore;
import com.airhacks.porcupine.execution.entity.Pipeline;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor; | /*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class RejectionsCounter implements RejectedExecutionHandler {
private RejectedExecutionHandler handler; | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/PipelineStore.java
// @ApplicationScoped
// public class PipelineStore {
//
// ConcurrentHashMap<String, Pipeline> pipelines;
//
// @PostConstruct
// public void init() {
// this.pipelines = new ConcurrentHashMap<>();
// }
//
// public Pipeline get(String name) {
// return this.pipelines.get(name);
// }
//
// public void put(String pipelineName, Pipeline pipeline) {
// this.pipelines.put(pipelineName, pipeline);
// }
//
// public Collection<Pipeline> pipelines() {
// return this.pipelines.values();
//
// }
//
// public Statistics getStatistics(String name) {
// Pipeline pipeline = this.pipelines.get(name);
// if (pipeline != null) {
// return pipeline.getStatistics();
// } else {
// return new Statistics();
// }
// }
//
// public int getNumberOfPipelines() {
// return this.pipelines.size();
// }
//
// public List<Statistics> getAllStatistics() {
// return this.pipelines.values().stream().
// map(p -> p.getStatistics()).
// collect(Collectors.toList());
// }
//
// public void clear() {
// this.pipelines.clear();
// }
//
// public Pipeline findPipeline(ThreadPoolExecutor executor) {
// return this.pipelines().stream().filter((p) -> p.manages(executor)).findFirst().orElse(null);
// }
//
// @PreDestroy
// public void shutdown() {
// this.pipelines.values().parallelStream().forEach(p -> p.shutdown());
// this.pipelines.clear();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java
// public class Pipeline {
//
// private final String pipelineName;
// private final InstrumentedThreadPoolExecutor tpe;
// private final AtomicLong rejectedTasks;
//
// public Pipeline(String pipelineName, InstrumentedThreadPoolExecutor tpe) {
// this.pipelineName = pipelineName;
// this.tpe = tpe;
// this.rejectedTasks = new AtomicLong();
// }
//
// public Statistics getStatistics() {
// int remainingQueueCapacity = this.tpe.getQueue().remainingCapacity();
// int minQueueCapacity = this.tpe.getMinRemainingQueueCapacity();
// int corePoolSize = this.tpe.getCorePoolSize();
// long completedTaskCount = this.tpe.getCompletedTaskCount();
// int activeThreadCount = this.tpe.getActiveCount();
// int largestThreadPoolSize = this.tpe.getLargestPoolSize();
// int currentThreadPoolSize = this.tpe.getPoolSize();
// long totalNumberOfTasks = this.tpe.getTaskCount();
// int maximumPoolSize = this.tpe.getMaximumPoolSize();
// RejectedExecutionHandler handler = this.tpe.getRejectedExecutionHandler();
// String rejectedExecutionHandlerName = null;
// if (handler != null) {
// rejectedExecutionHandlerName = handler.getClass().getSimpleName();
// }
// return new Statistics(this.pipelineName, remainingQueueCapacity, minQueueCapacity, completedTaskCount, activeThreadCount, corePoolSize, largestThreadPoolSize, currentThreadPoolSize, totalNumberOfTasks, maximumPoolSize, rejectedExecutionHandlerName, this.rejectedTasks.get());
//
// }
//
// public ExecutorService getExecutor() {
// return tpe;
// }
//
// public void shutdown() {
// this.tpe.shutdown();
// }
//
// public boolean manages(ThreadPoolExecutor executor) {
// return this.tpe == executor;
// }
//
// public void taskRejected() {
// this.rejectedTasks.incrementAndGet();
// }
//
// }
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/boundary/RejectionsCounter.java
import com.airhacks.porcupine.execution.control.PipelineStore;
import com.airhacks.porcupine.execution.entity.Pipeline;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class RejectionsCounter implements RejectedExecutionHandler {
private RejectedExecutionHandler handler; | private PipelineStore ps; |
AdamBien/porcupine | porcupine/src/main/java/com/airhacks/porcupine/execution/boundary/RejectionsCounter.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/PipelineStore.java
// @ApplicationScoped
// public class PipelineStore {
//
// ConcurrentHashMap<String, Pipeline> pipelines;
//
// @PostConstruct
// public void init() {
// this.pipelines = new ConcurrentHashMap<>();
// }
//
// public Pipeline get(String name) {
// return this.pipelines.get(name);
// }
//
// public void put(String pipelineName, Pipeline pipeline) {
// this.pipelines.put(pipelineName, pipeline);
// }
//
// public Collection<Pipeline> pipelines() {
// return this.pipelines.values();
//
// }
//
// public Statistics getStatistics(String name) {
// Pipeline pipeline = this.pipelines.get(name);
// if (pipeline != null) {
// return pipeline.getStatistics();
// } else {
// return new Statistics();
// }
// }
//
// public int getNumberOfPipelines() {
// return this.pipelines.size();
// }
//
// public List<Statistics> getAllStatistics() {
// return this.pipelines.values().stream().
// map(p -> p.getStatistics()).
// collect(Collectors.toList());
// }
//
// public void clear() {
// this.pipelines.clear();
// }
//
// public Pipeline findPipeline(ThreadPoolExecutor executor) {
// return this.pipelines().stream().filter((p) -> p.manages(executor)).findFirst().orElse(null);
// }
//
// @PreDestroy
// public void shutdown() {
// this.pipelines.values().parallelStream().forEach(p -> p.shutdown());
// this.pipelines.clear();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java
// public class Pipeline {
//
// private final String pipelineName;
// private final InstrumentedThreadPoolExecutor tpe;
// private final AtomicLong rejectedTasks;
//
// public Pipeline(String pipelineName, InstrumentedThreadPoolExecutor tpe) {
// this.pipelineName = pipelineName;
// this.tpe = tpe;
// this.rejectedTasks = new AtomicLong();
// }
//
// public Statistics getStatistics() {
// int remainingQueueCapacity = this.tpe.getQueue().remainingCapacity();
// int minQueueCapacity = this.tpe.getMinRemainingQueueCapacity();
// int corePoolSize = this.tpe.getCorePoolSize();
// long completedTaskCount = this.tpe.getCompletedTaskCount();
// int activeThreadCount = this.tpe.getActiveCount();
// int largestThreadPoolSize = this.tpe.getLargestPoolSize();
// int currentThreadPoolSize = this.tpe.getPoolSize();
// long totalNumberOfTasks = this.tpe.getTaskCount();
// int maximumPoolSize = this.tpe.getMaximumPoolSize();
// RejectedExecutionHandler handler = this.tpe.getRejectedExecutionHandler();
// String rejectedExecutionHandlerName = null;
// if (handler != null) {
// rejectedExecutionHandlerName = handler.getClass().getSimpleName();
// }
// return new Statistics(this.pipelineName, remainingQueueCapacity, minQueueCapacity, completedTaskCount, activeThreadCount, corePoolSize, largestThreadPoolSize, currentThreadPoolSize, totalNumberOfTasks, maximumPoolSize, rejectedExecutionHandlerName, this.rejectedTasks.get());
//
// }
//
// public ExecutorService getExecutor() {
// return tpe;
// }
//
// public void shutdown() {
// this.tpe.shutdown();
// }
//
// public boolean manages(ThreadPoolExecutor executor) {
// return this.tpe == executor;
// }
//
// public void taskRejected() {
// this.rejectedTasks.incrementAndGet();
// }
//
// }
| import com.airhacks.porcupine.execution.control.PipelineStore;
import com.airhacks.porcupine.execution.entity.Pipeline;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor; | /*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class RejectionsCounter implements RejectedExecutionHandler {
private RejectedExecutionHandler handler;
private PipelineStore ps;
public RejectionsCounter(RejectedExecutionHandler handler, PipelineStore pipeline) {
this.handler = handler;
this.ps = pipeline;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/control/PipelineStore.java
// @ApplicationScoped
// public class PipelineStore {
//
// ConcurrentHashMap<String, Pipeline> pipelines;
//
// @PostConstruct
// public void init() {
// this.pipelines = new ConcurrentHashMap<>();
// }
//
// public Pipeline get(String name) {
// return this.pipelines.get(name);
// }
//
// public void put(String pipelineName, Pipeline pipeline) {
// this.pipelines.put(pipelineName, pipeline);
// }
//
// public Collection<Pipeline> pipelines() {
// return this.pipelines.values();
//
// }
//
// public Statistics getStatistics(String name) {
// Pipeline pipeline = this.pipelines.get(name);
// if (pipeline != null) {
// return pipeline.getStatistics();
// } else {
// return new Statistics();
// }
// }
//
// public int getNumberOfPipelines() {
// return this.pipelines.size();
// }
//
// public List<Statistics> getAllStatistics() {
// return this.pipelines.values().stream().
// map(p -> p.getStatistics()).
// collect(Collectors.toList());
// }
//
// public void clear() {
// this.pipelines.clear();
// }
//
// public Pipeline findPipeline(ThreadPoolExecutor executor) {
// return this.pipelines().stream().filter((p) -> p.manages(executor)).findFirst().orElse(null);
// }
//
// @PreDestroy
// public void shutdown() {
// this.pipelines.values().parallelStream().forEach(p -> p.shutdown());
// this.pipelines.clear();
// }
//
// }
//
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Pipeline.java
// public class Pipeline {
//
// private final String pipelineName;
// private final InstrumentedThreadPoolExecutor tpe;
// private final AtomicLong rejectedTasks;
//
// public Pipeline(String pipelineName, InstrumentedThreadPoolExecutor tpe) {
// this.pipelineName = pipelineName;
// this.tpe = tpe;
// this.rejectedTasks = new AtomicLong();
// }
//
// public Statistics getStatistics() {
// int remainingQueueCapacity = this.tpe.getQueue().remainingCapacity();
// int minQueueCapacity = this.tpe.getMinRemainingQueueCapacity();
// int corePoolSize = this.tpe.getCorePoolSize();
// long completedTaskCount = this.tpe.getCompletedTaskCount();
// int activeThreadCount = this.tpe.getActiveCount();
// int largestThreadPoolSize = this.tpe.getLargestPoolSize();
// int currentThreadPoolSize = this.tpe.getPoolSize();
// long totalNumberOfTasks = this.tpe.getTaskCount();
// int maximumPoolSize = this.tpe.getMaximumPoolSize();
// RejectedExecutionHandler handler = this.tpe.getRejectedExecutionHandler();
// String rejectedExecutionHandlerName = null;
// if (handler != null) {
// rejectedExecutionHandlerName = handler.getClass().getSimpleName();
// }
// return new Statistics(this.pipelineName, remainingQueueCapacity, minQueueCapacity, completedTaskCount, activeThreadCount, corePoolSize, largestThreadPoolSize, currentThreadPoolSize, totalNumberOfTasks, maximumPoolSize, rejectedExecutionHandlerName, this.rejectedTasks.get());
//
// }
//
// public ExecutorService getExecutor() {
// return tpe;
// }
//
// public void shutdown() {
// this.tpe.shutdown();
// }
//
// public boolean manages(ThreadPoolExecutor executor) {
// return this.tpe == executor;
// }
//
// public void taskRejected() {
// this.rejectedTasks.incrementAndGet();
// }
//
// }
// Path: porcupine/src/main/java/com/airhacks/porcupine/execution/boundary/RejectionsCounter.java
import com.airhacks.porcupine.execution.control.PipelineStore;
import com.airhacks.porcupine.execution.entity.Pipeline;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/*
* Copyright 2016 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.boundary;
/**
*
* @author airhacks.com
*/
public class RejectionsCounter implements RejectedExecutionHandler {
private RejectedExecutionHandler handler;
private PipelineStore ps;
public RejectionsCounter(RejectedExecutionHandler handler, PipelineStore pipeline) {
this.handler = handler;
this.ps = pipeline;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { | Pipeline findPipeline = this.ps.findPipeline(executor); |
AdamBien/porcupine | porcupine/src/test/java/com/airhacks/porcupine/execution/control/ExecutorServiceInjectionTarget.java | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
| import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.enterprise.inject.Instance;
import javax.inject.Inject; | /*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.control;
/**
*
* @author airhacks.com
*/
public class ExecutorServiceInjectionTarget {
public final static String FIRST = "first";
public final static String SECOND = "second";
@Inject
@Dedicated
private ExecutorService first;
@Inject
@Dedicated
private ExecutorService second;
@Inject
@Dedicated(FIRST) | // Path: porcupine/src/main/java/com/airhacks/porcupine/execution/entity/Statistics.java
// @Alternative
// @XmlRootElement
// @XmlAccessorType(XmlAccessType.FIELD)
// public class Statistics {
//
// private String pipelineName;
// private int remainingQueueCapacity;
// private int minQueueCapacity;
// private long completedTaskCount;
// private int activeThreadCount;
// private int largestThreadPoolSize;
// private int currentThreadPoolSize;
// private long totalNumberOfTasks;
// private int maximumPoolSize;
// private String rejectedExecutionHandlerName;
// private long rejectedTasks;
// private int corePoolSize;
//
// public Statistics(String pipelineName, int remainingQueueCapacity, int minQueueCapacity, long completedTaskCount, int activeThreadCount, int corePoolSize, int largestThreadPoolSize, int currentThreadPoolSize, long totalNumberOfTasks, int maximumPoolSize, String rejectedExecutionHandlerName, long rejectedTasks) {
// this.pipelineName = pipelineName;
// this.remainingQueueCapacity = remainingQueueCapacity;
// this.minQueueCapacity = minQueueCapacity;
// this.completedTaskCount = completedTaskCount;
// this.activeThreadCount = activeThreadCount;
// this.corePoolSize = corePoolSize;
// this.largestThreadPoolSize = largestThreadPoolSize;
// this.currentThreadPoolSize = currentThreadPoolSize;
// this.totalNumberOfTasks = totalNumberOfTasks;
// this.maximumPoolSize = maximumPoolSize;
// this.rejectedTasks = rejectedTasks;
// this.rejectedExecutionHandlerName = rejectedExecutionHandlerName;
// }
//
// public Statistics() {
// }
//
// public int getRemainingQueueCapacity() {
// return remainingQueueCapacity;
// }
//
// public int getMinQueueCapacity() {
// return minQueueCapacity;
// }
//
// public long getCompletedTaskCount() {
// return completedTaskCount;
// }
//
// public int getActiveThreadCount() {
// return activeThreadCount;
// }
//
// public int getLargestThreadPoolSize() {
// return largestThreadPoolSize;
// }
//
// public int getCurrentThreadPoolSize() {
// return currentThreadPoolSize;
// }
//
// public long getTotalNumberOfTasks() {
// return totalNumberOfTasks;
// }
//
// public int getMaximumPoolSize() {
// return maximumPoolSize;
// }
//
// public long getRejectedTasks() {
// return rejectedTasks;
// }
//
// public String getPipelineName() {
// return pipelineName;
// }
//
// public String getRejectedExecutionHandlerName() {
// return rejectedExecutionHandlerName;
// }
//
// public int getCorePoolSize() {
// return corePoolSize;
// }
//
// @Override
// public String toString() {
// return "Statistics{" + "pipelineName=" + pipelineName + ", remainingQueueCapacity=" + remainingQueueCapacity + ", minQueueCapacity=" + minQueueCapacity + ", completedTaskCount=" + completedTaskCount + ", activeThreadCount=" + activeThreadCount + ", largestThreadPoolSize=" + largestThreadPoolSize + ", currentThreadPoolSize=" + currentThreadPoolSize + ", totalNumberOfTasks=" + totalNumberOfTasks + ", maximumPoolSize=" + maximumPoolSize + ", rejectedExecutionHandlerName=" + rejectedExecutionHandlerName + ", rejectedTasks=" + rejectedTasks + ", corePoolSize=" + corePoolSize + '}';
// }
//
// }
// Path: porcupine/src/test/java/com/airhacks/porcupine/execution/control/ExecutorServiceInjectionTarget.java
import com.airhacks.porcupine.execution.boundary.Dedicated;
import com.airhacks.porcupine.execution.entity.Statistics;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
/*
* Copyright 2015 Adam Bien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.airhacks.porcupine.execution.control;
/**
*
* @author airhacks.com
*/
public class ExecutorServiceInjectionTarget {
public final static String FIRST = "first";
public final static String SECOND = "second";
@Inject
@Dedicated
private ExecutorService first;
@Inject
@Dedicated
private ExecutorService second;
@Inject
@Dedicated(FIRST) | private Instance<Statistics> firstStatistics; |
Fedict/dcattools | tools/src/main/java/be/fedict/dcat/tools/LinkChecker.java | // Path: helpers/src/main/java/be/fedict/dcat/helpers/Fetcher.java
// public class Fetcher {
// private final static Logger logger = LoggerFactory.getLogger(Fetcher.class);
// private int delay = 1000;
//
// /**
// * Sleep (between HTTP requests)
// */
// public void sleep() {
// try {
// Thread.sleep(getDelay());
// } catch (InterruptedException ex) {
// }
// }
//
//
// /**
// * Get delay between HTTP requests
// *
// * @return
// */
// public int getDelay() {
// return delay;
// }
// /**
// * Set delay between HTTP requests (500 ms or higher)
// *
// * @param delay milliseconds
// */
// public void setDelay(int delay) {
// if (delay >= 500) {
// this.delay = delay;
// logger.info("Setting delay to {} ms", delay);
// } else {
// logger.warn("Delay of {} ms is too low", delay);
// }
// }
//
//
// /**
// * Make HTTP GET request, assuming UTF8 response
// *
// * @param url
// * @return String containing raw page or empty string
// * @throws IOException
// */
// public String makeRequest(URL url) throws IOException {
// return makeRequest(url, StandardCharsets.UTF_8);
// }
//
// /**
// * Make HTTP GET request, assuming a specific charset used in the response
// *
// * @param url
// * @param charset response charset
// * @return String containing raw page or empty string
// * @throws IOException
// */
// public String makeRequest(URL url, Charset charset) throws IOException {
// logger.info("Get request for page {}", url);
// Request request = Request.Get(url.toString());
// // some servers return 503 if no accept header is present
// request.addHeader(HttpHeaders.ACCEPT, "*/*");
// request.connectTimeout(240 * 1000);
// request.socketTimeout(240 * 1000);
// HttpResponse res = request.execute().returnResponse();
// // Return empty if the HTTP returns something faulty
// int status = res.getStatusLine().getStatusCode();
// if (status != 200) {
// logger.warn("HTTP code {} getting page {}", status, url);
// return "";
// }
//
// return EntityUtils.toString(res.getEntity(), charset);
// }
//
// /**
// * Make HTTP HEAD request
// *
// * @param url
// * @return
// * @throws IOException
// */
// public int makeHeadRequest(URL url) throws IOException {
// logger.info("Head request for {}", url);
// Request request = Request.Head(url.toString());
//
// return request.execute().returnResponse()
// .getStatusLine().getStatusCode();
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.fedict.dcat.helpers.Fetcher;
import java.io.BufferedReader;
import java.io.BufferedWriter;
| /*
* Copyright (c) 2016, FPS BOSA DG DT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.fedict.dcat.tools;
/**
* Simple link checker.
*
* @author Bart Hanssens <bart.hanssens@fedict.be>
*/
public class LinkChecker {
private final static Logger logger = LoggerFactory.getLogger(LinkChecker.class);
private final static String PROP_PREFIX = "be.fedict.dcat.tools.linkchecker";
private final static Properties prop = new Properties();
| // Path: helpers/src/main/java/be/fedict/dcat/helpers/Fetcher.java
// public class Fetcher {
// private final static Logger logger = LoggerFactory.getLogger(Fetcher.class);
// private int delay = 1000;
//
// /**
// * Sleep (between HTTP requests)
// */
// public void sleep() {
// try {
// Thread.sleep(getDelay());
// } catch (InterruptedException ex) {
// }
// }
//
//
// /**
// * Get delay between HTTP requests
// *
// * @return
// */
// public int getDelay() {
// return delay;
// }
// /**
// * Set delay between HTTP requests (500 ms or higher)
// *
// * @param delay milliseconds
// */
// public void setDelay(int delay) {
// if (delay >= 500) {
// this.delay = delay;
// logger.info("Setting delay to {} ms", delay);
// } else {
// logger.warn("Delay of {} ms is too low", delay);
// }
// }
//
//
// /**
// * Make HTTP GET request, assuming UTF8 response
// *
// * @param url
// * @return String containing raw page or empty string
// * @throws IOException
// */
// public String makeRequest(URL url) throws IOException {
// return makeRequest(url, StandardCharsets.UTF_8);
// }
//
// /**
// * Make HTTP GET request, assuming a specific charset used in the response
// *
// * @param url
// * @param charset response charset
// * @return String containing raw page or empty string
// * @throws IOException
// */
// public String makeRequest(URL url, Charset charset) throws IOException {
// logger.info("Get request for page {}", url);
// Request request = Request.Get(url.toString());
// // some servers return 503 if no accept header is present
// request.addHeader(HttpHeaders.ACCEPT, "*/*");
// request.connectTimeout(240 * 1000);
// request.socketTimeout(240 * 1000);
// HttpResponse res = request.execute().returnResponse();
// // Return empty if the HTTP returns something faulty
// int status = res.getStatusLine().getStatusCode();
// if (status != 200) {
// logger.warn("HTTP code {} getting page {}", status, url);
// return "";
// }
//
// return EntityUtils.toString(res.getEntity(), charset);
// }
//
// /**
// * Make HTTP HEAD request
// *
// * @param url
// * @return
// * @throws IOException
// */
// public int makeHeadRequest(URL url) throws IOException {
// logger.info("Head request for {}", url);
// Request request = Request.Head(url.toString());
//
// return request.execute().returnResponse()
// .getStatusLine().getStatusCode();
// }
// }
// Path: tools/src/main/java/be/fedict/dcat/tools/LinkChecker.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.fedict.dcat.helpers.Fetcher;
import java.io.BufferedReader;
import java.io.BufferedWriter;
/*
* Copyright (c) 2016, FPS BOSA DG DT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package be.fedict.dcat.tools;
/**
* Simple link checker.
*
* @author Bart Hanssens <bart.hanssens@fedict.be>
*/
public class LinkChecker {
private final static Logger logger = LoggerFactory.getLogger(LinkChecker.class);
private final static String PROP_PREFIX = "be.fedict.dcat.tools.linkchecker";
private final static Properties prop = new Properties();
| private final static Fetcher fetcher = new Fetcher();
|
fblupi/master_informatica-DSS | P3/BolivarFrancisco-p3/src/recurso/JugadorRecurso.java | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
| import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import modelo.Jugador;
import modelo.JugadorDao; | package recurso;
public class JugadorRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public JugadorRecurso(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
// Path: P3/BolivarFrancisco-p3/src/recurso/JugadorRecurso.java
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import modelo.Jugador;
import modelo.JugadorDao;
package recurso;
public class JugadorRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public JugadorRecurso(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) | public Jugador getJugador() { |
fblupi/master_informatica-DSS | P3/BolivarFrancisco-p3/src/recurso/JugadorRecurso.java | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
| import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import modelo.Jugador;
import modelo.JugadorDao; | package recurso;
public class JugadorRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public JugadorRecurso(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Jugador getJugador() { | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
// Path: P3/BolivarFrancisco-p3/src/recurso/JugadorRecurso.java
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import modelo.Jugador;
import modelo.JugadorDao;
package recurso;
public class JugadorRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public JugadorRecurso(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Jugador getJugador() { | Jugador jugador = JugadorDao.INSTANCE.getModel().get(id); |
fblupi/master_informatica-DSS | P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
| import java.util.HashMap;
import java.util.Map;
import modelo.Jugador; | package modelo;
public enum JugadorDao {
INSTANCE; // para implementar el patron singleton
| // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
import java.util.HashMap;
import java.util.Map;
import modelo.Jugador;
package modelo;
public enum JugadorDao {
INSTANCE; // para implementar el patron singleton
| private Map<String, Jugador> proveedorContenidos = new HashMap<>(); |
fblupi/master_informatica-DSS | P2-previo/jpa.simple/src/jpa/simple/principal/Principal.java | // Path: P2-previo/jpa.simple/src/jpa/simple/modelo/Completo.java
// @Entity
// public class Completo {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String resumen;
// private String descripcion;
// public String getResumen() {
// return resumen;
// }
// public void setResumen(String resumen) {
// this.resumen = resumen;
// }
// public String getDescripcion() {
// return descripcion;
// }
// public void setDescripcion(String descripcion) {
// this.descripcion = descripcion;
// }
// @Override
// public String toString() {
// return "Completo [resumen=" + resumen + ", descripcion=" + descripcion + "]";
// }
// }
| import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import jpa.simple.modelo.Completo; | package jpa.simple.principal;
public class Principal {
private static final String PERSISTENCE_UNIT_NAME = "completos";
private static EntityManagerFactory factoria;
public static void main(String[] args) {
factoria = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factoria.createEntityManager();
// Leer las entradas existentes y escribir en la consola
Query q = em.createQuery("select t from Completo t");
| // Path: P2-previo/jpa.simple/src/jpa/simple/modelo/Completo.java
// @Entity
// public class Completo {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String resumen;
// private String descripcion;
// public String getResumen() {
// return resumen;
// }
// public void setResumen(String resumen) {
// this.resumen = resumen;
// }
// public String getDescripcion() {
// return descripcion;
// }
// public void setDescripcion(String descripcion) {
// this.descripcion = descripcion;
// }
// @Override
// public String toString() {
// return "Completo [resumen=" + resumen + ", descripcion=" + descripcion + "]";
// }
// }
// Path: P2-previo/jpa.simple/src/jpa/simple/principal/Principal.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import jpa.simple.modelo.Completo;
package jpa.simple.principal;
public class Principal {
private static final String PERSISTENCE_UNIT_NAME = "completos";
private static EntityManagerFactory factoria;
public static void main(String[] args) {
factoria = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factoria.createEntityManager();
// Leer las entradas existentes y escribir en la consola
Query q = em.createQuery("select t from Completo t");
| List<Completo> completoLista = q.getResultList(); |
fblupi/master_informatica-DSS | P3/BolivarFrancisco-p3/src/recurso/JugadoresRecurso.java | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import modelo.Jugador;
import modelo.JugadorDao; | package recurso;
@Path("/jugadores")
public class JugadoresRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
@GET
@Produces(MediaType.TEXT_XML) | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
// Path: P3/BolivarFrancisco-p3/src/recurso/JugadoresRecurso.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import modelo.Jugador;
import modelo.JugadorDao;
package recurso;
@Path("/jugadores")
public class JugadoresRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
@GET
@Produces(MediaType.TEXT_XML) | public List<Jugador> getJugadoresBrowser() { |
fblupi/master_informatica-DSS | P3/BolivarFrancisco-p3/src/recurso/JugadoresRecurso.java | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import modelo.Jugador;
import modelo.JugadorDao; | package recurso;
@Path("/jugadores")
public class JugadoresRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
@GET
@Produces(MediaType.TEXT_XML)
public List<Jugador> getJugadoresBrowser() {
List<Jugador> jugadores = new ArrayList<Jugador>(); | // Path: P3/BolivarFrancisco-p3/src/modelo/Jugador.java
// @XmlRootElement
// public class Jugador {
// private String id;
// private String nombre;
// private String nombreCompleto;
// private String posicion;
// private int calidad;
//
// public Jugador() {
//
// }
//
// public Jugador(String id, String nombre, String posicion, int calidad) {
// this.id = id;
// this.nombre = nombre;
// this.posicion = posicion;
// this.calidad = calidad;
// }
//
// public String getId() {
// return nombre;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getNombre() {
// return nombre;
// }
//
// public void setNombre(String nombre) {
// this.nombre = nombre;
// }
//
// public String getNombreCompleto() {
// return nombreCompleto;
// }
//
// public void setNombreCompleto(String nombreCompleto) {
// this.nombreCompleto = nombreCompleto;
// }
//
// public String getPosicion() {
// return posicion;
// }
//
// public void setPosicion(String posicion) {
// this.posicion = posicion;
// }
//
// public int getCalidad() {
// return calidad;
// }
//
// public void setCalidad(int calidad) {
// this.calidad = calidad;
// }
// }
//
// Path: P3/BolivarFrancisco-p3/src/modelo/JugadorDao.java
// public enum JugadorDao {
// INSTANCE; // para implementar el patron singleton
//
// private Map<String, Jugador> proveedorContenidos = new HashMap<>();
//
// private JugadorDao() {
// Jugador jugador = new Jugador("1", "Jimmy", "Extremo derecho", 94);
// jugador.setNombreCompleto("Jimmy Natali");
// proveedorContenidos.put("1", jugador);
// jugador = new Jugador("2", "Josito", "Carrilero derecho", 72);
// jugador.setNombreCompleto("José Manuel Avilés");
// proveedorContenidos.put("2", jugador);
// }
//
// public Map<String, Jugador> getModel(){
// return proveedorContenidos;
// }
// }
// Path: P3/BolivarFrancisco-p3/src/recurso/JugadoresRecurso.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import modelo.Jugador;
import modelo.JugadorDao;
package recurso;
@Path("/jugadores")
public class JugadoresRecurso {
@Context
UriInfo uriInfo;
@Context
Request request;
@GET
@Produces(MediaType.TEXT_XML)
public List<Jugador> getJugadoresBrowser() {
List<Jugador> jugadores = new ArrayList<Jugador>(); | jugadores.addAll(JugadorDao.INSTANCE.getModel().values()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.