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 |
|---|---|---|---|---|---|---|
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/SettingsFragment.java | // Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_ALLOW_EXTERNAL = "prefAllowExternal";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_AUTO_NAME = "prefAutoName";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_AUTO_START = "prefAutoStart";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_HOST = "prefHost";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_LIVE_SYNC = "prefLiveSync";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_PASS = "prefPass";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_PROVIDER = "prefProvider";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_USERNAME = "prefUsername";
| import static androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_ALLOW_EXTERNAL;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_AUTO_NAME;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_AUTO_START;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_HOST;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_LIVE_SYNC;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_PASS;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_PROVIDER;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_USERNAME;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.preference.TwoStatePreference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map; | fragment.setTargetFragment(this, 0);
fragment.show(getParentFragmentManager(), "ListPreferenceDialogWithMessageFragment");
} else {
super.onDisplayPreferenceDialog(preference);
}
}
/**
* Set various listeners
*/
private void setListeners() {
final Preference prefLiveSync = findPreference(KEY_LIVE_SYNC);
final Preference prefUsername = findPreference(KEY_USERNAME);
final Preference prefPass = findPreference(KEY_PASS);
final Preference prefHost = findPreference(KEY_HOST);
// on change listeners
if (prefLiveSync != null) {
prefLiveSync.setOnPreferenceChangeListener(liveSyncChanged);
}
if (prefUsername != null) {
prefUsername.setOnPreferenceChangeListener(serverSetupChanged);
}
if (prefPass != null) {
prefPass.setOnPreferenceChangeListener(serverSetupChanged);
}
if (prefHost != null) {
prefHost.setOnPreferenceChangeListener(serverSetupChanged);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
final Preference prefAutoStart = findPreference(KEY_AUTO_START); | // Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_ALLOW_EXTERNAL = "prefAllowExternal";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_AUTO_NAME = "prefAutoName";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_AUTO_START = "prefAutoStart";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_HOST = "prefHost";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_LIVE_SYNC = "prefLiveSync";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_PASS = "prefPass";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_PROVIDER = "prefProvider";
//
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsActivity.java
// public static final String KEY_USERNAME = "prefUsername";
// Path: app/src/main/java/net/fabiszewski/ulogger/SettingsFragment.java
import static androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_ALLOW_EXTERNAL;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_AUTO_NAME;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_AUTO_START;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_HOST;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_LIVE_SYNC;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_PASS;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_PROVIDER;
import static net.fabiszewski.ulogger.SettingsActivity.KEY_USERNAME;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.preference.TwoStatePreference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
fragment.setTargetFragment(this, 0);
fragment.show(getParentFragmentManager(), "ListPreferenceDialogWithMessageFragment");
} else {
super.onDisplayPreferenceDialog(preference);
}
}
/**
* Set various listeners
*/
private void setListeners() {
final Preference prefLiveSync = findPreference(KEY_LIVE_SYNC);
final Preference prefUsername = findPreference(KEY_USERNAME);
final Preference prefPass = findPreference(KEY_PASS);
final Preference prefHost = findPreference(KEY_HOST);
// on change listeners
if (prefLiveSync != null) {
prefLiveSync.setOnPreferenceChangeListener(liveSyncChanged);
}
if (prefUsername != null) {
prefUsername.setOnPreferenceChangeListener(serverSetupChanged);
}
if (prefPass != null) {
prefPass.setOnPreferenceChangeListener(serverSetupChanged);
}
if (prefHost != null) {
prefHost.setOnPreferenceChangeListener(serverSetupChanged);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
final Preference prefAutoStart = findPreference(KEY_AUTO_START); | final Preference prefAllowExternal = findPreference(KEY_ALLOW_EXTERNAL); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/LoggerService.java | // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
| import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager; | thread = new HandlerThread("LoggerThread");
thread.start();
looper = thread.getLooper();
// keep database open during whole service runtime
db = DbAccess.getInstance();
db.open(this);
}
/**
* Request location updates, start web synchronization if needed
* @return True on success, false otherwise
*/
private boolean initializeLocationUpdates() {
if (Logger.DEBUG) { Log.d(TAG, "[initializeLocationUpdates]"); }
try {
locationHelper.updatePreferences();
locationHelper.requestLocationUpdates(locationListener, looper);
setRunning(true);
sendBroadcast(BROADCAST_LOCATION_STARTED);
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode(); | // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerService.java
import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
thread = new HandlerThread("LoggerThread");
thread.start();
looper = thread.getLooper();
// keep database open during whole service runtime
db = DbAccess.getInstance();
db.open(this);
}
/**
* Request location updates, start web synchronization if needed
* @return True on success, false otherwise
*/
private boolean initializeLocationUpdates() {
if (Logger.DEBUG) { Log.d(TAG, "[initializeLocationUpdates]"); }
try {
locationHelper.updatePreferences();
locationHelper.requestLocationUpdates(locationListener, looper);
setRunning(true);
sendBroadcast(BROADCAST_LOCATION_STARTED);
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode(); | if (errorCode == E_DISABLED) { |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/LoggerService.java | // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
| import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager; | looper = thread.getLooper();
// keep database open during whole service runtime
db = DbAccess.getInstance();
db.open(this);
}
/**
* Request location updates, start web synchronization if needed
* @return True on success, false otherwise
*/
private boolean initializeLocationUpdates() {
if (Logger.DEBUG) { Log.d(TAG, "[initializeLocationUpdates]"); }
try {
locationHelper.updatePreferences();
locationHelper.requestLocationUpdates(locationListener, looper);
setRunning(true);
sendBroadcast(BROADCAST_LOCATION_STARTED);
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode();
if (errorCode == E_DISABLED) {
sendBroadcast(BROADCAST_LOCATION_DISABLED); | // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerService.java
import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
looper = thread.getLooper();
// keep database open during whole service runtime
db = DbAccess.getInstance();
db.open(this);
}
/**
* Request location updates, start web synchronization if needed
* @return True on success, false otherwise
*/
private boolean initializeLocationUpdates() {
if (Logger.DEBUG) { Log.d(TAG, "[initializeLocationUpdates]"); }
try {
locationHelper.updatePreferences();
locationHelper.requestLocationUpdates(locationListener, looper);
setRunning(true);
sendBroadcast(BROADCAST_LOCATION_STARTED);
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode();
if (errorCode == E_DISABLED) {
sendBroadcast(BROADCAST_LOCATION_DISABLED); | } else if (errorCode == E_PERMISSION) { |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/LoggerService.java | // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
| import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager; |
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode();
if (errorCode == E_DISABLED) {
sendBroadcast(BROADCAST_LOCATION_DISABLED);
} else if (errorCode == E_PERMISSION) {
sendBroadcast(BROADCAST_LOCATION_PERMISSION_DENIED);
}
}
return false;
}
/**
* Start foreground service
*
* @param intent Intent
* @param flags Flags
* @param startId Unique id
* @return Always returns START_STICKY
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Logger.DEBUG) { Log.d(TAG, "[onStartCommand]"); }
| // Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_DISABLED = 2;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerTask.java
// static final int E_PERMISSION = 1;
//
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
// public final static String UPDATED_PREFS = "extra_updated_prefs";
// Path: app/src/main/java/net/fabiszewski/ulogger/LoggerService.java
import static net.fabiszewski.ulogger.LoggerTask.E_DISABLED;
import static net.fabiszewski.ulogger.LoggerTask.E_PERMISSION;
import static net.fabiszewski.ulogger.MainActivity.UPDATED_PREFS;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
syncIntent = new Intent(getApplicationContext(), WebSyncService.class);
if (locationHelper.isLiveSync() && DbAccess.needsSync(this)) {
getApplicationContext().startService(syncIntent);
}
return true;
} catch (LocationHelper.LoggerException e) {
int errorCode = e.getCode();
if (errorCode == E_DISABLED) {
sendBroadcast(BROADCAST_LOCATION_DISABLED);
} else if (errorCode == E_PERMISSION) {
sendBroadcast(BROADCAST_LOCATION_PERMISSION_DENIED);
}
}
return false;
}
/**
* Start foreground service
*
* @param intent Intent
* @param flags Flags
* @param startId Unique id
* @return Always returns START_STICKY
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Logger.DEBUG) { Log.d(TAG, "[onStartCommand]"); }
| if (intent != null && intent.getBooleanExtra(UPDATED_PREFS, false)) { |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/MainActivity.java | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
| import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService; | onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Reread user preferences
*/
private void updatePreferences() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
preferenceUnits = prefs.getString(SettingsActivity.KEY_UNITS, getString(R.string.pref_units_default));
preferenceMinTimeMillis = Long.parseLong(prefs.getString(SettingsActivity.KEY_MIN_TIME, getString(R.string.pref_mintime_default))) * 1000;
preferenceLiveSync = prefs.getBoolean(SettingsActivity.KEY_LIVE_SYNC, false);
preferenceHost = prefs.getString(SettingsActivity.KEY_HOST, "").replaceAll("/+$", "");
}
/**
* Display warning if track name is not set
*/
public void showNoTrackWarning() {
showToast(getString(R.string.no_track_warning));
}
/**
* Start export service
*/
private void startExport() {
if (db.countPositions() > 0) {
try { | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService;
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Reread user preferences
*/
private void updatePreferences() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
preferenceUnits = prefs.getString(SettingsActivity.KEY_UNITS, getString(R.string.pref_units_default));
preferenceMinTimeMillis = Long.parseLong(prefs.getString(SettingsActivity.KEY_MIN_TIME, getString(R.string.pref_mintime_default))) * 1000;
preferenceLiveSync = prefs.getBoolean(SettingsActivity.KEY_LIVE_SYNC, false);
preferenceHost = prefs.getString(SettingsActivity.KEY_HOST, "").replaceAll("/+$", "");
}
/**
* Display warning if track name is not set
*/
public void showNoTrackWarning() {
showToast(getString(R.string.no_track_warning));
}
/**
* Start export service
*/
private void startExport() {
if (db.countPositions() > 0) {
try { | getExportUri.launch(DbAccess.getTrackName(this) + GPX_EXTENSION); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/MainActivity.java | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
| import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService; |
/**
* Display warning if track name is not set
*/
public void showNoTrackWarning() {
showToast(getString(R.string.no_track_warning));
}
/**
* Start export service
*/
private void startExport() {
if (db.countPositions() > 0) {
try {
getExportUri.launch(DbAccess.getTrackName(this) + GPX_EXTENSION);
} catch (ActivityNotFoundException e) {
showToast(getString(R.string.cannot_open_picker), Toast.LENGTH_LONG);
}
} else {
showToast(getString(R.string.nothing_to_export));
}
}
private void clearTrack() {
if (LoggerService.isRunning()) {
showToast(getString(R.string.logger_running_warning));
return;
}
if (DbAccess.getTrackName(MainActivity.this) != null) { | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService;
/**
* Display warning if track name is not set
*/
public void showNoTrackWarning() {
showToast(getString(R.string.no_track_warning));
}
/**
* Start export service
*/
private void startExport() {
if (db.countPositions() > 0) {
try {
getExportUri.launch(DbAccess.getTrackName(this) + GPX_EXTENSION);
} catch (ActivityNotFoundException e) {
showToast(getString(R.string.cannot_open_picker), Toast.LENGTH_LONG);
}
} else {
showToast(getString(R.string.nothing_to_export));
}
}
private void clearTrack() {
if (LoggerService.isRunning()) {
showToast(getString(R.string.logger_running_warning));
return;
}
if (DbAccess.getTrackName(MainActivity.this) != null) { | showConfirm(MainActivity.this, |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/MainActivity.java | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
| import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService; | currentFragment.onResume();
}
}
);
}
}
/**
* Display toast message
* @param text Message
*/
private void showToast(CharSequence text) {
showToast(text, Toast.LENGTH_SHORT);
}
/**
* Display toast message
* @param text Message
* @param duration Duration
*/
private void showToast(CharSequence text, int duration) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
/**
* Display About dialog
*/
private void showAbout() { | // Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static AlertDialog showAlert(Activity context, CharSequence title, int layoutResource, int iconResource) {
// @SuppressLint("InflateParams")
// View view = context.getLayoutInflater().inflate(layoutResource, null, false);
// AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle(title);
// alertDialog.setView(view);
// if (iconResource > 0) {
// alertDialog.setIcon(iconResource);
// }
// alertDialog.show();
// return alertDialog;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/Alert.java
// static void showConfirm(Context context, CharSequence title, CharSequence message,
// DialogInterface.OnClickListener yesCallback) {
// AlertDialog alertDialog = initDialog(context, title, message);
// alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), yesCallback);
// alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
// (dialog, which) -> dialog.dismiss());
// alertDialog.show();
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/GpxExportTask.java
// public static final String GPX_EXTENSION = ".gpx";
// Path: app/src/main/java/net/fabiszewski/ulogger/MainActivity.java
import static androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import static net.fabiszewski.ulogger.Alert.showAlert;
import static net.fabiszewski.ulogger.Alert.showConfirm;
import static net.fabiszewski.ulogger.GpxExportTask.GPX_EXTENSION;
import static java.util.concurrent.Executors.newCachedThreadPool;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import java.util.concurrent.ExecutorService;
currentFragment.onResume();
}
}
);
}
}
/**
* Display toast message
* @param text Message
*/
private void showToast(CharSequence text) {
showToast(text, Toast.LENGTH_SHORT);
}
/**
* Display toast message
* @param text Message
* @param duration Duration
*/
private void showToast(CharSequence text, int duration) {
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
/**
* Display About dialog
*/
private void showAbout() { | final AlertDialog dialog = showAlert(MainActivity.this, |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/ImageTask.java | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
| import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache; | uiHandler.post(() -> onPostExecute(result));
}
isRunning = false;
}
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri; | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageTask.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache;
uiHandler.post(() -> onPostExecute(result));
}
isRunning = false;
}
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri; | getPersistablePermission(activity, uri); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/ImageTask.java | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
| import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache; | }
isRunning = false;
}
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri); | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageTask.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache;
}
isRunning = false;
}
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri); | thumbnail = getThumbnail(activity, uri); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/ImageTask.java | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
| import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache; | }
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri);
thumbnail = getThumbnail(activity, uri);
} else { | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageTask.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache;
}
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri);
thumbnail = getThumbnail(activity, uri);
} else { | Bitmap bitmap = getResampledBitmap(activity, uri, dstWidth); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/ImageTask.java | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
| import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache; |
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri);
thumbnail = getThumbnail(activity, uri);
} else {
Bitmap bitmap = getResampledBitmap(activity, uri, dstWidth); | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageTask.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache;
public void cancel() {
if (Logger.DEBUG) { Log.d(TAG, "[task cancelled]"); }
isCancelled = true;
}
public boolean isRunning() {
return isRunning;
}
@WorkerThread
private ImageTaskResult doInBackground() {
if (Logger.DEBUG) { Log.d(TAG, "[doInBackground]"); }
Activity activity = getActivity();
if (activity == null) {
return null;
}
ImageTaskResult result = null;
try {
Uri savedUri;
Bitmap thumbnail;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
int dstWidth = Integer.parseInt(prefs.getString(SettingsActivity.KEY_IMAGE_SIZE, activity.getString(R.string.pref_imagesize_default)));
if (dstWidth == 0) {
savedUri = uri;
getPersistablePermission(activity, uri);
thumbnail = getThumbnail(activity, uri);
} else {
Bitmap bitmap = getResampledBitmap(activity, uri, dstWidth); | savedUri = saveToCache(activity, bitmap); |
bfabiszewski/ulogger-android | app/src/main/java/net/fabiszewski/ulogger/ImageTask.java | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
| import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache; | }
@UiThread
private void onPostExecute(@Nullable ImageTaskResult result) {
ImageTaskCallback callback = weakCallback.get();
if (callback != null && callback.getActivity() != null) {
if (result == null) {
callback.onImageTaskFailure(errorMessage);
} else {
callback.onImageTaskCompleted(result.savedUri, result.thumbnail);
}
}
}
@Nullable
private Activity getActivity() {
ImageTaskCallback callback = weakCallback.get();
if (callback != null) {
return callback.getActivity();
}
return null;
}
/**
* Try to clean image cache
* @param result Task result
*/
private void cleanUp(ImageTaskResult result) {
Activity activity = getActivity();
if (result != null && activity != null) { | // Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void clearImageCache(@NonNull Context context) {
// File dir = context.getCacheDir();
// clearImages(dir);
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static void getPersistablePermission(@NonNull Context context, @NonNull Uri uri) {
// try {
// context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
// } catch (SecurityException e) {
// if (Logger.DEBUG) { Log.d(TAG, "[getPersistablePermission failed for " + uri + "]"); }
// }
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getResampledBitmap(@NonNull Context context, @NonNull Uri uri, int dstWidth) throws IOException {
// ContentResolver cr = context.getContentResolver();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// try (InputStream is = cr.openInputStream(uri)) {
// BitmapFactory.decodeStream(is, null, options);
// }
// int srcWidth = Math.max(options.outWidth, options.outHeight);
// int scale = srcWidth / dstWidth;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded scale: " + scale + "]"); }
// options = new BitmapFactory.Options();
// Bitmap bitmap = null;
// boolean retry = false;
// do {
// try {
// if (scale > 1) {
// options.inScaled = true;
// options.inSampleSize = 1;
// options.inDensity = srcWidth;
// options.inTargetDensity = dstWidth * options.inSampleSize;
// }
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, options);
// }
// } catch (OutOfMemoryError e) {
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded OutOfMemoryError]"); }
// if (retry) {
// throw new IOException("Out of memory");
// } else if (scale > 1) {
// retry = true;
// options.inSampleSize = scale;
// if (Logger.DEBUG) { Log.d(TAG, "[resampleIfNeeded try sampling]"); }
// }
// }
// } while (retry);
//
// if (bitmap == null) {
// throw new IOException("Failed to decode image");
// }
//
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Bitmap getThumbnail(@NonNull Context context, @NonNull Uri uri) throws IOException {
// int sizePx = getThumbnailSize(context);
// Bitmap bitmap;
// ContentResolver cr = context.getContentResolver();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// bitmap = cr.loadThumbnail(uri, new Size(sizePx, sizePx), null);
// } else {
// try (InputStream is = cr.openInputStream(uri)) {
// bitmap = BitmapFactory.decodeStream(is, null, null);
// }
//
// bitmap = ThumbnailUtils.extractThumbnail(bitmap, sizePx, sizePx);
// }
// bitmap = fixImageOrientation(context, uri, bitmap);
// return bitmap;
// }
//
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageHelper.java
// static Uri saveToCache(@NonNull Context context, @NonNull Bitmap bitmap) throws IOException {
// String filename = getUniqueName() + EXT_JPG;
// File outFile = new File(context.getCacheDir(), filename);
// try (FileOutputStream os = new FileOutputStream(outFile)) {
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
// }
// return Uri.fromFile(outFile);
// }
// Path: app/src/main/java/net/fabiszewski/ulogger/ImageTask.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.annotation.WorkerThread;
import androidx.preference.PreferenceManager;
import java.io.IOException;
import java.lang.ref.WeakReference;
import static net.fabiszewski.ulogger.ImageHelper.clearImageCache;
import static net.fabiszewski.ulogger.ImageHelper.getPersistablePermission;
import static net.fabiszewski.ulogger.ImageHelper.getResampledBitmap;
import static net.fabiszewski.ulogger.ImageHelper.getThumbnail;
import static net.fabiszewski.ulogger.ImageHelper.saveToCache;
}
@UiThread
private void onPostExecute(@Nullable ImageTaskResult result) {
ImageTaskCallback callback = weakCallback.get();
if (callback != null && callback.getActivity() != null) {
if (result == null) {
callback.onImageTaskFailure(errorMessage);
} else {
callback.onImageTaskCompleted(result.savedUri, result.thumbnail);
}
}
}
@Nullable
private Activity getActivity() {
ImageTaskCallback callback = weakCallback.get();
if (callback != null) {
return callback.getActivity();
}
return null;
}
/**
* Try to clean image cache
* @param result Task result
*/
private void cleanUp(ImageTaskResult result) {
Activity activity = getActivity();
if (result != null && activity != null) { | clearImageCache(activity.getApplicationContext()); |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineHistoryAdapter.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/RoutineHistoryFragment.java
// public class RoutineHistoryFragment extends BaseFragment {
//
// private OnFragmentInteractionListener mListener;
// private RoutineStatsDataHolder mDataHolder = RoutineStatsDataHolder.getInstance();
//
// private RecyclerView mRecyclerView;
// private RoutineHistoryAdapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
//
// public RoutineHistoryFragment() {
// // Required empty public constructor
// }
//
// public static RoutineHistoryFragment newInstance() {
// return new RoutineHistoryFragment();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_routine_history, container, false);
//
// mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_routine_history);
// mLayoutManager = new LinearLayoutManager(getActivity());
// mRecyclerView.setLayoutManager(mLayoutManager);
//
// RoutineStats routineStats = mDataHolder.getRoutineStats();
//
// mAdapter = new RoutineHistoryAdapter(mListener, routineStats);
//
// mRecyclerView.setAdapter(mAdapter);
//
// // Display the empty view if there are no previous exercise sessions
// TextView emptyView = (TextView) view.findViewById(R.id.empty_view_routine_history);
// if (routineStats == null || routineStats.isEmpty()) {
// mRecyclerView.setVisibility(View.GONE);
// emptyView.setVisibility(View.VISIBLE);
// } else {
// mRecyclerView.setVisibility(View.VISIBLE);
// emptyView.setVisibility(View.GONE);
// }
//
// return view;
// }
//
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// mListener = null;
// }
//
// public interface OnFragmentInteractionListener {
// void exerciseSelected(String exerciseName);
// }
// }
| import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
import edu.umn.paull011.evolveworkoutlogger.fragments.RoutineHistoryFragment; | package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 7/19/2016.
* An adapter that populates the Routine History RecyclerView with cards showing details
* for each routine session.
*/
public class RoutineHistoryAdapter extends RecyclerView.Adapter<RoutineHistoryAdapter.ViewHolder> {
public static final String TAG = RoutineHistoryAdapter.class.getSimpleName(); | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/RoutineHistoryFragment.java
// public class RoutineHistoryFragment extends BaseFragment {
//
// private OnFragmentInteractionListener mListener;
// private RoutineStatsDataHolder mDataHolder = RoutineStatsDataHolder.getInstance();
//
// private RecyclerView mRecyclerView;
// private RoutineHistoryAdapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
//
// public RoutineHistoryFragment() {
// // Required empty public constructor
// }
//
// public static RoutineHistoryFragment newInstance() {
// return new RoutineHistoryFragment();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_routine_history, container, false);
//
// mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_routine_history);
// mLayoutManager = new LinearLayoutManager(getActivity());
// mRecyclerView.setLayoutManager(mLayoutManager);
//
// RoutineStats routineStats = mDataHolder.getRoutineStats();
//
// mAdapter = new RoutineHistoryAdapter(mListener, routineStats);
//
// mRecyclerView.setAdapter(mAdapter);
//
// // Display the empty view if there are no previous exercise sessions
// TextView emptyView = (TextView) view.findViewById(R.id.empty_view_routine_history);
// if (routineStats == null || routineStats.isEmpty()) {
// mRecyclerView.setVisibility(View.GONE);
// emptyView.setVisibility(View.VISIBLE);
// } else {
// mRecyclerView.setVisibility(View.VISIBLE);
// emptyView.setVisibility(View.GONE);
// }
//
// return view;
// }
//
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// mListener = null;
// }
//
// public interface OnFragmentInteractionListener {
// void exerciseSelected(String exerciseName);
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineHistoryAdapter.java
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
import edu.umn.paull011.evolveworkoutlogger.fragments.RoutineHistoryFragment;
package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 7/19/2016.
* An adapter that populates the Routine History RecyclerView with cards showing details
* for each routine session.
*/
public class RoutineHistoryAdapter extends RecyclerView.Adapter<RoutineHistoryAdapter.ViewHolder> {
public static final String TAG = RoutineHistoryAdapter.class.getSimpleName(); | public RoutineHistoryFragment.OnFragmentInteractionListener mListener; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineHistoryAdapter.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/RoutineHistoryFragment.java
// public class RoutineHistoryFragment extends BaseFragment {
//
// private OnFragmentInteractionListener mListener;
// private RoutineStatsDataHolder mDataHolder = RoutineStatsDataHolder.getInstance();
//
// private RecyclerView mRecyclerView;
// private RoutineHistoryAdapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
//
// public RoutineHistoryFragment() {
// // Required empty public constructor
// }
//
// public static RoutineHistoryFragment newInstance() {
// return new RoutineHistoryFragment();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_routine_history, container, false);
//
// mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_routine_history);
// mLayoutManager = new LinearLayoutManager(getActivity());
// mRecyclerView.setLayoutManager(mLayoutManager);
//
// RoutineStats routineStats = mDataHolder.getRoutineStats();
//
// mAdapter = new RoutineHistoryAdapter(mListener, routineStats);
//
// mRecyclerView.setAdapter(mAdapter);
//
// // Display the empty view if there are no previous exercise sessions
// TextView emptyView = (TextView) view.findViewById(R.id.empty_view_routine_history);
// if (routineStats == null || routineStats.isEmpty()) {
// mRecyclerView.setVisibility(View.GONE);
// emptyView.setVisibility(View.VISIBLE);
// } else {
// mRecyclerView.setVisibility(View.VISIBLE);
// emptyView.setVisibility(View.GONE);
// }
//
// return view;
// }
//
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// mListener = null;
// }
//
// public interface OnFragmentInteractionListener {
// void exerciseSelected(String exerciseName);
// }
// }
| import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
import edu.umn.paull011.evolveworkoutlogger.fragments.RoutineHistoryFragment; | package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 7/19/2016.
* An adapter that populates the Routine History RecyclerView with cards showing details
* for each routine session.
*/
public class RoutineHistoryAdapter extends RecyclerView.Adapter<RoutineHistoryAdapter.ViewHolder> {
public static final String TAG = RoutineHistoryAdapter.class.getSimpleName();
public RoutineHistoryFragment.OnFragmentInteractionListener mListener; | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/RoutineHistoryFragment.java
// public class RoutineHistoryFragment extends BaseFragment {
//
// private OnFragmentInteractionListener mListener;
// private RoutineStatsDataHolder mDataHolder = RoutineStatsDataHolder.getInstance();
//
// private RecyclerView mRecyclerView;
// private RoutineHistoryAdapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
//
// public RoutineHistoryFragment() {
// // Required empty public constructor
// }
//
// public static RoutineHistoryFragment newInstance() {
// return new RoutineHistoryFragment();
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_routine_history, container, false);
//
// mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_routine_history);
// mLayoutManager = new LinearLayoutManager(getActivity());
// mRecyclerView.setLayoutManager(mLayoutManager);
//
// RoutineStats routineStats = mDataHolder.getRoutineStats();
//
// mAdapter = new RoutineHistoryAdapter(mListener, routineStats);
//
// mRecyclerView.setAdapter(mAdapter);
//
// // Display the empty view if there are no previous exercise sessions
// TextView emptyView = (TextView) view.findViewById(R.id.empty_view_routine_history);
// if (routineStats == null || routineStats.isEmpty()) {
// mRecyclerView.setVisibility(View.GONE);
// emptyView.setVisibility(View.VISIBLE);
// } else {
// mRecyclerView.setVisibility(View.VISIBLE);
// emptyView.setVisibility(View.GONE);
// }
//
// return view;
// }
//
// @Override
// public void onAttach(Context context) {
// super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
// }
//
// @Override
// public void onDetach() {
// super.onDetach();
// mListener = null;
// }
//
// public interface OnFragmentInteractionListener {
// void exerciseSelected(String exerciseName);
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineHistoryAdapter.java
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
import edu.umn.paull011.evolveworkoutlogger.fragments.RoutineHistoryFragment;
package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 7/19/2016.
* An adapter that populates the Routine History RecyclerView with cards showing details
* for each routine session.
*/
public class RoutineHistoryAdapter extends RecyclerView.Adapter<RoutineHistoryAdapter.ViewHolder> {
public static final String TAG = RoutineHistoryAdapter.class.getSimpleName();
public RoutineHistoryFragment.OnFragmentInteractionListener mListener; | public RoutineStats mRoutineStats; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementData.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/TimeStringHelper.java
// public class TimeStringHelper {
//
// /***
// * Get the amount of time in seconds from a time string of the format hh:mm:ss.
// * Will also accept mm:ss input
// * @param timeString Time string to parse
// * @return amount of time in seconds
// */
// public static int parseTimeString(String timeString) {
// String[] timeComponents = timeString.split(":");
// int seconds = 0;
// if (timeComponents.length == 3) { // has hour component
// seconds += Integer.valueOf(timeComponents[0]) * 3600;
// seconds += Integer.valueOf(timeComponents[1]) * 60;
// seconds += Integer.valueOf(timeComponents[2]);
// }
// else if (timeComponents.length == 2) {
// seconds += Integer.valueOf(timeComponents[0]) * 60;
// seconds += Integer.valueOf(timeComponents[1]);
// }
// else if (timeComponents.length == 1) {
// seconds += Integer.valueOf(timeComponents[0]);
// }
// return seconds;
// }
//
// /***
// * If the given string is shorter than the desired length, pad out the beginning of
// * the string with zeros so that the string has a length of desiredLength
// * @param numString An unpadded number string
// * @param desiredLength The desired length of the string with zeroes prepended
// * @return numString padded with leading zeros
// */
// public static String fillOutLeadingZeros(String numString, int desiredLength) {
// String result = "";
// int numZerosToAdd = desiredLength - numString.length();
// if (numZerosToAdd <= 0) {
// return numString;
// }
// else {
// for (int i = 0; i < numZerosToAdd; i++) {
// result += "0";
// }
// result += numString;
// return result;
// }
// }
//
// /***
// * Make a time-formatted string from an integer number of seconds
// */
// public static String createTimeString(int seconds) {
// int hours = seconds/3600;
// int minutes = (seconds % 3600)/60;
// seconds = seconds % 60;
// String result;
// if (hours != 0) {
// result = String.valueOf(hours) + ":"
// + fillOutLeadingZeros(String.valueOf(minutes),2) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else if (minutes != 0) {
// result = String.valueOf(minutes) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else {
// result = "0:" + fillOutLeadingZeros(String.valueOf(seconds), 2);
// }
// return result;
// }
// }
| import edu.umn.paull011.evolveworkoutlogger.helper_classes.TimeStringHelper; | public float getMeasurement() {
return mMeasurement;
}
public void setMeasurement(float m){
mMeasurement = m;
}
public Unit getUnit() {
return mUnit;
}
public void copyData(MeasurementData other){
mCategory = other.mCategory;
mMeasurement = other.mMeasurement;
}
public String display() {
String unit = mUnit.getDisplayName();
String number = getDisplayNumber();
if (mCategory == MeasurementCategory.TIME) {
return number;
}
else {
return number + " " + unit;
}
}
private String getDisplayNumber() {
if (mCategory == MeasurementCategory.TIME) { | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/TimeStringHelper.java
// public class TimeStringHelper {
//
// /***
// * Get the amount of time in seconds from a time string of the format hh:mm:ss.
// * Will also accept mm:ss input
// * @param timeString Time string to parse
// * @return amount of time in seconds
// */
// public static int parseTimeString(String timeString) {
// String[] timeComponents = timeString.split(":");
// int seconds = 0;
// if (timeComponents.length == 3) { // has hour component
// seconds += Integer.valueOf(timeComponents[0]) * 3600;
// seconds += Integer.valueOf(timeComponents[1]) * 60;
// seconds += Integer.valueOf(timeComponents[2]);
// }
// else if (timeComponents.length == 2) {
// seconds += Integer.valueOf(timeComponents[0]) * 60;
// seconds += Integer.valueOf(timeComponents[1]);
// }
// else if (timeComponents.length == 1) {
// seconds += Integer.valueOf(timeComponents[0]);
// }
// return seconds;
// }
//
// /***
// * If the given string is shorter than the desired length, pad out the beginning of
// * the string with zeros so that the string has a length of desiredLength
// * @param numString An unpadded number string
// * @param desiredLength The desired length of the string with zeroes prepended
// * @return numString padded with leading zeros
// */
// public static String fillOutLeadingZeros(String numString, int desiredLength) {
// String result = "";
// int numZerosToAdd = desiredLength - numString.length();
// if (numZerosToAdd <= 0) {
// return numString;
// }
// else {
// for (int i = 0; i < numZerosToAdd; i++) {
// result += "0";
// }
// result += numString;
// return result;
// }
// }
//
// /***
// * Make a time-formatted string from an integer number of seconds
// */
// public static String createTimeString(int seconds) {
// int hours = seconds/3600;
// int minutes = (seconds % 3600)/60;
// seconds = seconds % 60;
// String result;
// if (hours != 0) {
// result = String.valueOf(hours) + ":"
// + fillOutLeadingZeros(String.valueOf(minutes),2) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else if (minutes != 0) {
// result = String.valueOf(minutes) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else {
// result = "0:" + fillOutLeadingZeros(String.valueOf(seconds), 2);
// }
// return result;
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementData.java
import edu.umn.paull011.evolveworkoutlogger.helper_classes.TimeStringHelper;
public float getMeasurement() {
return mMeasurement;
}
public void setMeasurement(float m){
mMeasurement = m;
}
public Unit getUnit() {
return mUnit;
}
public void copyData(MeasurementData other){
mCategory = other.mCategory;
mMeasurement = other.mMeasurement;
}
public String display() {
String unit = mUnit.getDisplayName();
String number = getDisplayNumber();
if (mCategory == MeasurementCategory.TIME) {
return number;
}
else {
return number + " " + unit;
}
}
private String getDisplayNumber() {
if (mCategory == MeasurementCategory.TIME) { | return TimeStringHelper.createTimeString((int) mMeasurement); |
mpsonic/Evolve-Workout-Logger | app/src/test/java/UnitTest.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Unit.java
// public enum Unit {
//
// // Public
// REPS(),
// KILOGRAMS(false),
// METERS(false),
// KILOMETERS(false),
// POUNDS(true),
// FEET(true),
// MILES(true),
// TIME(),
// SECONDS(),
// MINUTES(),
// HOURS();
//
// // Private
// private final boolean mUniversal;
// private final boolean mImperial;
//
// Unit(){
// this.mUniversal = true;
// this.mImperial = true;
// }
//
// Unit(boolean imperial){
// this.mUniversal = false;
// this.mImperial = imperial;
// }
//
// /***
// * Get the Unit enum from its name or abbreviation
// * @param name unit name
// * @return unit enum
// */
// public static Unit getFromName(String name) {
// Unit result = null;
// name = name.toUpperCase();
// switch (name) {
// case "REPS":
// result = REPS;
// break;
// case "KILOGRAMS":
// result = KILOGRAMS;
// break;
// case "METERS":
// result = METERS;
// break;
// case "KILOMETERS":
// result = KILOMETERS;
// break;
// case "POUNDS":
// result = POUNDS;
// break;
// case "LBS":
// result = POUNDS;
// break;
// case "FEET":
// result = FEET;
// break;
// case "FT":
// result = FEET;
// break;
// case "MILES":
// result = MILES;
// break;
// case "MI":
// result = MILES;
// break;
// case "TIME":
// result = TIME;
// break;
// case "SECONDS":
// result = SECONDS;
// break;
// case "S":
// result = SECONDS;
// break;
// case "MINUTES":
// result = MINUTES;
// break;
// case "HOURS":
// result = HOURS;
// break;
// case "H":
// result = HOURS;
// break;
// }
// return result;
// }
//
// public boolean isUniversal() {
// return mUniversal;
// }
//
// public boolean isImperial() {
// return mImperial;
// }
//
// /***
// * Get the name to be displayed (usually an abbreviation) for the unit
// * @return display name
// */
// public String getDisplayName() {
// switch (this) {
// case REPS:
// return "reps";
// case KILOGRAMS:
// return "kg";
// case METERS:
// return "m";
// case KILOMETERS:
// return "km";
// case POUNDS:
// return "lbs";
// case FEET:
// return "ft";
// case MILES:
// return "mi";
// case TIME:
// return "";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// }
// return "";
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import edu.umn.paull011.evolveworkoutlogger.data_structures.Unit; |
/**
* Testing the Unit enumeration
*
* Created by Mitchell on 1/4/2016.
*/
public class UnitTest {
@Test
public void testUnits(){ | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Unit.java
// public enum Unit {
//
// // Public
// REPS(),
// KILOGRAMS(false),
// METERS(false),
// KILOMETERS(false),
// POUNDS(true),
// FEET(true),
// MILES(true),
// TIME(),
// SECONDS(),
// MINUTES(),
// HOURS();
//
// // Private
// private final boolean mUniversal;
// private final boolean mImperial;
//
// Unit(){
// this.mUniversal = true;
// this.mImperial = true;
// }
//
// Unit(boolean imperial){
// this.mUniversal = false;
// this.mImperial = imperial;
// }
//
// /***
// * Get the Unit enum from its name or abbreviation
// * @param name unit name
// * @return unit enum
// */
// public static Unit getFromName(String name) {
// Unit result = null;
// name = name.toUpperCase();
// switch (name) {
// case "REPS":
// result = REPS;
// break;
// case "KILOGRAMS":
// result = KILOGRAMS;
// break;
// case "METERS":
// result = METERS;
// break;
// case "KILOMETERS":
// result = KILOMETERS;
// break;
// case "POUNDS":
// result = POUNDS;
// break;
// case "LBS":
// result = POUNDS;
// break;
// case "FEET":
// result = FEET;
// break;
// case "FT":
// result = FEET;
// break;
// case "MILES":
// result = MILES;
// break;
// case "MI":
// result = MILES;
// break;
// case "TIME":
// result = TIME;
// break;
// case "SECONDS":
// result = SECONDS;
// break;
// case "S":
// result = SECONDS;
// break;
// case "MINUTES":
// result = MINUTES;
// break;
// case "HOURS":
// result = HOURS;
// break;
// case "H":
// result = HOURS;
// break;
// }
// return result;
// }
//
// public boolean isUniversal() {
// return mUniversal;
// }
//
// public boolean isImperial() {
// return mImperial;
// }
//
// /***
// * Get the name to be displayed (usually an abbreviation) for the unit
// * @return display name
// */
// public String getDisplayName() {
// switch (this) {
// case REPS:
// return "reps";
// case KILOGRAMS:
// return "kg";
// case METERS:
// return "m";
// case KILOMETERS:
// return "km";
// case POUNDS:
// return "lbs";
// case FEET:
// return "ft";
// case MILES:
// return "mi";
// case TIME:
// return "";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// }
// return "";
// }
// }
// Path: app/src/test/java/UnitTest.java
import org.junit.Assert;
import org.junit.Test;
import edu.umn.paull011.evolveworkoutlogger.data_structures.Unit;
/**
* Testing the Unit enumeration
*
* Created by Mitchell on 1/4/2016.
*/
public class UnitTest {
@Test
public void testUnits(){ | Unit reps = Unit.REPS; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/ExerciseStats.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/SortedDateStringList.java
// public class SortedDateStringList {
// ArrayList<Date> sortedDates = new ArrayList<>(4);
// DateFormat dateFormat;
// Boolean mSorted = false;
//
// public SortedDateStringList(DateFormat dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// public boolean isEmpty() {
// return sortedDates.size() == 0;
// }
//
// public boolean add(Date date) {
// if (this.contains(date)) {
// return false;
// }
// else {
// sortedDates.add(date);
// mSorted = false;
// return true;
// }
// /*int size = sortedDates.size();
// Date d1, d2;
//
// if (size == 1) {
// d1 = sortedDates.get(0);
// if (d1.compareTo(date) > 0) {
// sortedDates.add(date);
// } else {
// sortedDates.add(0, date);
// }
// return true;
// } else if (size > 1) {
// for (int i = 0; i < sortedDates.size() - 1; i++) {
// d1 = sortedDates.get(i);
// d2 = sortedDates.get(i + 1);
// if (d1.compareTo(date) > 0 && d2.compareTo(date) < 0) {
// sortedDates.add(i + 1, date);
// return true;
// }
// }
// }
// sortedDates.add(date);
// return true;*/
// }
//
// public String getDateString(int i) {
// if (!mSorted) {
// Collections.sort(sortedDates, new Comparator<Date>() {
// @Override
// public int compare(Date date, Date d2) {
// return (int)(d2.getTime() - date.getTime())/(86400);
// }
// });
// mSorted = true;
// }
// return dateFormat.format(sortedDates.get(i));
// }
//
// public boolean contains(Date date) {
// String newDateString = dateFormat.format(date);
// for (Date d : sortedDates) {
// if (newDateString.equals(dateFormat.format(d))) {
// return true;
// }
// }
// return false;
// }
// }
| import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.SortedDateStringList; | package edu.umn.paull011.evolveworkoutlogger.data_structures;
/**
* A class for holding statistics about an Exercise
*
* Created by Mitchell on 6/18/2016.
*/
public class ExerciseStats {
private HashMap<String, List<Set>> mSetData;
private DateFormat mDateFormat; | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/SortedDateStringList.java
// public class SortedDateStringList {
// ArrayList<Date> sortedDates = new ArrayList<>(4);
// DateFormat dateFormat;
// Boolean mSorted = false;
//
// public SortedDateStringList(DateFormat dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// public boolean isEmpty() {
// return sortedDates.size() == 0;
// }
//
// public boolean add(Date date) {
// if (this.contains(date)) {
// return false;
// }
// else {
// sortedDates.add(date);
// mSorted = false;
// return true;
// }
// /*int size = sortedDates.size();
// Date d1, d2;
//
// if (size == 1) {
// d1 = sortedDates.get(0);
// if (d1.compareTo(date) > 0) {
// sortedDates.add(date);
// } else {
// sortedDates.add(0, date);
// }
// return true;
// } else if (size > 1) {
// for (int i = 0; i < sortedDates.size() - 1; i++) {
// d1 = sortedDates.get(i);
// d2 = sortedDates.get(i + 1);
// if (d1.compareTo(date) > 0 && d2.compareTo(date) < 0) {
// sortedDates.add(i + 1, date);
// return true;
// }
// }
// }
// sortedDates.add(date);
// return true;*/
// }
//
// public String getDateString(int i) {
// if (!mSorted) {
// Collections.sort(sortedDates, new Comparator<Date>() {
// @Override
// public int compare(Date date, Date d2) {
// return (int)(d2.getTime() - date.getTime())/(86400);
// }
// });
// mSorted = true;
// }
// return dateFormat.format(sortedDates.get(i));
// }
//
// public boolean contains(Date date) {
// String newDateString = dateFormat.format(date);
// for (Date d : sortedDates) {
// if (newDateString.equals(dateFormat.format(d))) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/ExerciseStats.java
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.SortedDateStringList;
package edu.umn.paull011.evolveworkoutlogger.data_structures;
/**
* A class for holding statistics about an Exercise
*
* Created by Mitchell on 6/18/2016.
*/
public class ExerciseStats {
private HashMap<String, List<Set>> mSetData;
private DateFormat mDateFormat; | private SortedDateStringList mSortedDates; |
mpsonic/Evolve-Workout-Logger | app/src/test/java/MeasurementDataTest.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementCategory.java
// public enum MeasurementCategory {
// REPS(0, 5),
// WEIGHT(1, 0),
// DISTANCE(2, 0),
// TIME(3, 300);
//
// MeasurementCategory(int value, float defaultMeasurement){
// mValue = value;
// mDefaultMeasurement = defaultMeasurement;
// }
//
// public int value(){
// return mValue;
// }
//
// public static MeasurementCategory getFromName(String name) {
// MeasurementCategory category = null;
// switch (name) {
// case "REPS":
// category = REPS;
// break;
// case "WEIGHT":
// category = WEIGHT;
// break;
// case "DISTANCE":
// category = DISTANCE;
// break;
// case "TIME":
// category = TIME;
// break;
// }
// return category;
// }
//
// public Unit getDefaultUnit(boolean imperial){
// Unit result;
// switch (mValue){
// case 0:
// result = Unit.REPS;
// break;
// case 1:
// if (imperial)
// result = Unit.POUNDS;
// else
// result = Unit.KILOGRAMS;
// break;
// case 2:
// if (imperial)
// result = Unit.MILES;
// else
// result = Unit.KILOMETERS;
// break;
// case 3:
// result = Unit.MINUTES;
// break;
// default:
// result = null;
// }
// return result;
// }
//
// public float getDefaultMeasurement() {
// return mDefaultMeasurement;
// }
//
// // Private
// private final int mValue;
// private final float mDefaultMeasurement;
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementData.java
// public class MeasurementData{
//
// private static final String TAG = MeasurementData.class.getSimpleName();
// private MeasurementCategory mCategory;
// private float mMeasurement;
// private Unit mUnit;
//
//
// // Public
// public MeasurementData(){}
//
// public MeasurementData(MeasurementCategory category, float measurement, Unit unit) {
// mCategory = category;
// mMeasurement = measurement;
// mUnit = unit;
// }
//
// public MeasurementData(MeasurementCategory category, float measurement) {
// mCategory = category;
// mMeasurement = measurement;
// mUnit = category.getDefaultUnit(true);
// }
//
// public MeasurementCategory getCategory() {
// return mCategory;
// }
//
// public void setCategory(MeasurementCategory category){
// mCategory = category;
// }
//
// public float getMeasurement() {
// return mMeasurement;
// }
//
// public void setMeasurement(float m){
// mMeasurement = m;
// }
//
// public Unit getUnit() {
// return mUnit;
// }
//
// public void copyData(MeasurementData other){
// mCategory = other.mCategory;
// mMeasurement = other.mMeasurement;
// }
//
// public String display() {
// String unit = mUnit.getDisplayName();
// String number = getDisplayNumber();
// if (mCategory == MeasurementCategory.TIME) {
// return number;
// }
// else {
// return number + " " + unit;
// }
// }
//
// private String getDisplayNumber() {
// if (mCategory == MeasurementCategory.TIME) {
// return TimeStringHelper.createTimeString((int) mMeasurement);
// }
// if (isInteger()) {
// return String.valueOf((int) mMeasurement);
// }
// return String.valueOf(mMeasurement);
// }
//
// private String getTimeDisplayNumber() {
// if (mUnit == Unit.HOURS) {
// return String.valueOf(mMeasurement / 3600);
// } else if (mUnit == Unit.MINUTES) {
// return String.valueOf(mMeasurement / 60);
// } else {
// return String.valueOf((int) mMeasurement);
// }
// }
//
// private boolean isInteger() {
// return (Math.round(mMeasurement) == mMeasurement);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// // Objects of the same class?
// if (getClass() != obj.getClass())
// return false;
// MeasurementData other = (MeasurementData) obj;
// return mCategory == other.mCategory && mMeasurement == other.mMeasurement;
// }
//
// }
| import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import edu.umn.paull011.evolveworkoutlogger.data_structures.MeasurementCategory;
import edu.umn.paull011.evolveworkoutlogger.data_structures.MeasurementData; |
/**
*
* Testing the MeasurementData class
*
* Created by Mitchell on 1/4/2016.
*/
public class MeasurementDataTest {
private MeasurementData data;
@Before
public void setUp() { | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementCategory.java
// public enum MeasurementCategory {
// REPS(0, 5),
// WEIGHT(1, 0),
// DISTANCE(2, 0),
// TIME(3, 300);
//
// MeasurementCategory(int value, float defaultMeasurement){
// mValue = value;
// mDefaultMeasurement = defaultMeasurement;
// }
//
// public int value(){
// return mValue;
// }
//
// public static MeasurementCategory getFromName(String name) {
// MeasurementCategory category = null;
// switch (name) {
// case "REPS":
// category = REPS;
// break;
// case "WEIGHT":
// category = WEIGHT;
// break;
// case "DISTANCE":
// category = DISTANCE;
// break;
// case "TIME":
// category = TIME;
// break;
// }
// return category;
// }
//
// public Unit getDefaultUnit(boolean imperial){
// Unit result;
// switch (mValue){
// case 0:
// result = Unit.REPS;
// break;
// case 1:
// if (imperial)
// result = Unit.POUNDS;
// else
// result = Unit.KILOGRAMS;
// break;
// case 2:
// if (imperial)
// result = Unit.MILES;
// else
// result = Unit.KILOMETERS;
// break;
// case 3:
// result = Unit.MINUTES;
// break;
// default:
// result = null;
// }
// return result;
// }
//
// public float getDefaultMeasurement() {
// return mDefaultMeasurement;
// }
//
// // Private
// private final int mValue;
// private final float mDefaultMeasurement;
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/MeasurementData.java
// public class MeasurementData{
//
// private static final String TAG = MeasurementData.class.getSimpleName();
// private MeasurementCategory mCategory;
// private float mMeasurement;
// private Unit mUnit;
//
//
// // Public
// public MeasurementData(){}
//
// public MeasurementData(MeasurementCategory category, float measurement, Unit unit) {
// mCategory = category;
// mMeasurement = measurement;
// mUnit = unit;
// }
//
// public MeasurementData(MeasurementCategory category, float measurement) {
// mCategory = category;
// mMeasurement = measurement;
// mUnit = category.getDefaultUnit(true);
// }
//
// public MeasurementCategory getCategory() {
// return mCategory;
// }
//
// public void setCategory(MeasurementCategory category){
// mCategory = category;
// }
//
// public float getMeasurement() {
// return mMeasurement;
// }
//
// public void setMeasurement(float m){
// mMeasurement = m;
// }
//
// public Unit getUnit() {
// return mUnit;
// }
//
// public void copyData(MeasurementData other){
// mCategory = other.mCategory;
// mMeasurement = other.mMeasurement;
// }
//
// public String display() {
// String unit = mUnit.getDisplayName();
// String number = getDisplayNumber();
// if (mCategory == MeasurementCategory.TIME) {
// return number;
// }
// else {
// return number + " " + unit;
// }
// }
//
// private String getDisplayNumber() {
// if (mCategory == MeasurementCategory.TIME) {
// return TimeStringHelper.createTimeString((int) mMeasurement);
// }
// if (isInteger()) {
// return String.valueOf((int) mMeasurement);
// }
// return String.valueOf(mMeasurement);
// }
//
// private String getTimeDisplayNumber() {
// if (mUnit == Unit.HOURS) {
// return String.valueOf(mMeasurement / 3600);
// } else if (mUnit == Unit.MINUTES) {
// return String.valueOf(mMeasurement / 60);
// } else {
// return String.valueOf((int) mMeasurement);
// }
// }
//
// private boolean isInteger() {
// return (Math.round(mMeasurement) == mMeasurement);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// // Objects of the same class?
// if (getClass() != obj.getClass())
// return false;
// MeasurementData other = (MeasurementData) obj;
// return mCategory == other.mCategory && mMeasurement == other.mMeasurement;
// }
//
// }
// Path: app/src/test/java/MeasurementDataTest.java
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import edu.umn.paull011.evolveworkoutlogger.data_structures.MeasurementCategory;
import edu.umn.paull011.evolveworkoutlogger.data_structures.MeasurementData;
/**
*
* Testing the MeasurementData class
*
* Created by Mitchell on 1/4/2016.
*/
public class MeasurementDataTest {
private MeasurementData data;
@Before
public void setUp() { | data = new MeasurementData(MeasurementCategory.REPS, 10); |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineSessionService.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineSession.java
// public class RoutineSession {
//
// // Private
// private Routine mRoutine;
// private long mId;
// private Date mDate;
// private boolean mCompleted;
// private ArrayList<ExerciseSession> mExerciseSessions;
// private String mNotes;
// private static final String TAG = RoutineSession.class.getSimpleName();
//
// // Public
// public RoutineSession(Routine routine, boolean createExerciseSessions){
// mRoutine = routine;
// mId = -1;
// mDate = new Date(Calendar.getInstance().getTimeInMillis());
// mCompleted = false;
// mNotes = "";
// int numExercises = routine.getNumExercises();
// mExerciseSessions = new ArrayList<>(numExercises);
// boolean increment;
//
// if (createExerciseSessions) {
// Exercise exercise;
// ExerciseSession exerciseSession;
// for(int i = 0; i < numExercises; i++){
// exercise = routine.getExercise(i);
// exerciseSession = exercise.createNewExerciseSession();
// mExerciseSessions.add(exerciseSession);
// }
// }
// }
//
// public void setId(long id) {
// mId = id;
// }
//
// public long getId() {
// return mId;
// }
//
// public Routine getRoutine() {
// return mRoutine;
// }
//
// public void addNewExerciseSessionFromExercise(Exercise exercise, boolean addToRoutine){
// ExerciseSession exerciseSession = exercise.createNewExerciseSession();
// mExerciseSessions.add(exerciseSession);
// if(addToRoutine)
// mRoutine.addExercise(exercise);
// }
//
// public void addExerciseSession(ExerciseSession session) {
// mExerciseSessions.add(session);
// }
//
// public void removeExerciseSession(int index){
// mExerciseSessions.remove(index);
// }
//
//
// public ExerciseSession getExerciseSession(int index){
// return mExerciseSessions.get(index);
// }
//
//
// public int getExerciseSessionCount(){
// return mExerciseSessions.size();
// }
//
// public Date getDate(){
// return mDate;
// }
//
//
// public void setDate(Date date){
// mDate = date;
// }
//
// public String getNotes() {
// return mNotes;
// }
//
// public void setNotes(String notes) {
// mNotes = notes;
// }
//
// public boolean isCompleted() {
// return mCompleted;
// }
//
// public void finish() {
// mCompleted = true;
// }
//
// public void swapExerciseSessions(int fromPosition, int toPosition) {
// if (BuildConfig.DEBUG) {
// if (fromPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (fromPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (toPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (toPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (fromPosition != toPosition) {
// throw new AssertionError();
// }
// }
// ExerciseSession from = mExerciseSessions.get(fromPosition);
// ExerciseSession to = mExerciseSessions.get(toPosition);
// mExerciseSessions.set(fromPosition, to);
// mExerciseSessions.set(toPosition, from);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// // Objects of the same class?
// if (!(obj instanceof RoutineSession)) {return false;}
// RoutineSession other = (RoutineSession) obj;
// // Do the routine sessions have the same exercise sessions?
// if (mExerciseSessions.size() != other.mExerciseSessions.size()){
// return false;
// }
// if (this.isCompleted() != other.isCompleted()) {
// return false;
// }
// for(int i = 0; i < mExerciseSessions.size(); i++){
// if (!mExerciseSessions.get(i).equals(other.mExerciseSessions.get(i)))
// return false;
// }
// return true;
// }
// }
| import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineSession; | package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 1/18/2016.
*
* Service that handles changes / progress to the currently active routine session.
*
*/
public class RoutineSessionService extends Service {
// Binder that clients receive
private final IBinder mBinder = new LocalBinder();
// The routine session to be manipulated | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineSession.java
// public class RoutineSession {
//
// // Private
// private Routine mRoutine;
// private long mId;
// private Date mDate;
// private boolean mCompleted;
// private ArrayList<ExerciseSession> mExerciseSessions;
// private String mNotes;
// private static final String TAG = RoutineSession.class.getSimpleName();
//
// // Public
// public RoutineSession(Routine routine, boolean createExerciseSessions){
// mRoutine = routine;
// mId = -1;
// mDate = new Date(Calendar.getInstance().getTimeInMillis());
// mCompleted = false;
// mNotes = "";
// int numExercises = routine.getNumExercises();
// mExerciseSessions = new ArrayList<>(numExercises);
// boolean increment;
//
// if (createExerciseSessions) {
// Exercise exercise;
// ExerciseSession exerciseSession;
// for(int i = 0; i < numExercises; i++){
// exercise = routine.getExercise(i);
// exerciseSession = exercise.createNewExerciseSession();
// mExerciseSessions.add(exerciseSession);
// }
// }
// }
//
// public void setId(long id) {
// mId = id;
// }
//
// public long getId() {
// return mId;
// }
//
// public Routine getRoutine() {
// return mRoutine;
// }
//
// public void addNewExerciseSessionFromExercise(Exercise exercise, boolean addToRoutine){
// ExerciseSession exerciseSession = exercise.createNewExerciseSession();
// mExerciseSessions.add(exerciseSession);
// if(addToRoutine)
// mRoutine.addExercise(exercise);
// }
//
// public void addExerciseSession(ExerciseSession session) {
// mExerciseSessions.add(session);
// }
//
// public void removeExerciseSession(int index){
// mExerciseSessions.remove(index);
// }
//
//
// public ExerciseSession getExerciseSession(int index){
// return mExerciseSessions.get(index);
// }
//
//
// public int getExerciseSessionCount(){
// return mExerciseSessions.size();
// }
//
// public Date getDate(){
// return mDate;
// }
//
//
// public void setDate(Date date){
// mDate = date;
// }
//
// public String getNotes() {
// return mNotes;
// }
//
// public void setNotes(String notes) {
// mNotes = notes;
// }
//
// public boolean isCompleted() {
// return mCompleted;
// }
//
// public void finish() {
// mCompleted = true;
// }
//
// public void swapExerciseSessions(int fromPosition, int toPosition) {
// if (BuildConfig.DEBUG) {
// if (fromPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (fromPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (toPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (toPosition < mExerciseSessions.size()) {
// throw new AssertionError();
// }
// if (fromPosition != toPosition) {
// throw new AssertionError();
// }
// }
// ExerciseSession from = mExerciseSessions.get(fromPosition);
// ExerciseSession to = mExerciseSessions.get(toPosition);
// mExerciseSessions.set(fromPosition, to);
// mExerciseSessions.set(toPosition, from);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// // Objects of the same class?
// if (!(obj instanceof RoutineSession)) {return false;}
// RoutineSession other = (RoutineSession) obj;
// // Do the routine sessions have the same exercise sessions?
// if (mExerciseSessions.size() != other.mExerciseSessions.size()){
// return false;
// }
// if (this.isCompleted() != other.isCompleted()) {
// return false;
// }
// for(int i = 0; i < mExerciseSessions.size(); i++){
// if (!mExerciseSessions.get(i).equals(other.mExerciseSessions.get(i)))
// return false;
// }
// return true;
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineSessionService.java
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineSession;
package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* Created by Mitchell on 1/18/2016.
*
* Service that handles changes / progress to the currently active routine session.
*
*/
public class RoutineSessionService extends Service {
// Binder that clients receive
private final IBinder mBinder = new LocalBinder();
// The routine session to be manipulated | private RoutineSession mRoutineSession; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/components/ButtonEditText.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/TimeStringHelper.java
// public class TimeStringHelper {
//
// /***
// * Get the amount of time in seconds from a time string of the format hh:mm:ss.
// * Will also accept mm:ss input
// * @param timeString Time string to parse
// * @return amount of time in seconds
// */
// public static int parseTimeString(String timeString) {
// String[] timeComponents = timeString.split(":");
// int seconds = 0;
// if (timeComponents.length == 3) { // has hour component
// seconds += Integer.valueOf(timeComponents[0]) * 3600;
// seconds += Integer.valueOf(timeComponents[1]) * 60;
// seconds += Integer.valueOf(timeComponents[2]);
// }
// else if (timeComponents.length == 2) {
// seconds += Integer.valueOf(timeComponents[0]) * 60;
// seconds += Integer.valueOf(timeComponents[1]);
// }
// else if (timeComponents.length == 1) {
// seconds += Integer.valueOf(timeComponents[0]);
// }
// return seconds;
// }
//
// /***
// * If the given string is shorter than the desired length, pad out the beginning of
// * the string with zeros so that the string has a length of desiredLength
// * @param numString An unpadded number string
// * @param desiredLength The desired length of the string with zeroes prepended
// * @return numString padded with leading zeros
// */
// public static String fillOutLeadingZeros(String numString, int desiredLength) {
// String result = "";
// int numZerosToAdd = desiredLength - numString.length();
// if (numZerosToAdd <= 0) {
// return numString;
// }
// else {
// for (int i = 0; i < numZerosToAdd; i++) {
// result += "0";
// }
// result += numString;
// return result;
// }
// }
//
// /***
// * Make a time-formatted string from an integer number of seconds
// */
// public static String createTimeString(int seconds) {
// int hours = seconds/3600;
// int minutes = (seconds % 3600)/60;
// seconds = seconds % 60;
// String result;
// if (hours != 0) {
// result = String.valueOf(hours) + ":"
// + fillOutLeadingZeros(String.valueOf(minutes),2) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else if (minutes != 0) {
// result = String.valueOf(minutes) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else {
// result = "0:" + fillOutLeadingZeros(String.valueOf(seconds), 2);
// }
// return result;
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.TimeStringHelper; | mEditText.setRawInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME);
}
else {
mEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}
if (mHint != null) {
mEditText.setHint(mHint);
}
else {
refreshEditTextWithUnit();
}
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (mUpdateNumberAfterTextChanged) {
String text = mEditText.getText().toString();
try {
if (!mIsTime) {
mNumber = Float.valueOf(text);
}
else { | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/TimeStringHelper.java
// public class TimeStringHelper {
//
// /***
// * Get the amount of time in seconds from a time string of the format hh:mm:ss.
// * Will also accept mm:ss input
// * @param timeString Time string to parse
// * @return amount of time in seconds
// */
// public static int parseTimeString(String timeString) {
// String[] timeComponents = timeString.split(":");
// int seconds = 0;
// if (timeComponents.length == 3) { // has hour component
// seconds += Integer.valueOf(timeComponents[0]) * 3600;
// seconds += Integer.valueOf(timeComponents[1]) * 60;
// seconds += Integer.valueOf(timeComponents[2]);
// }
// else if (timeComponents.length == 2) {
// seconds += Integer.valueOf(timeComponents[0]) * 60;
// seconds += Integer.valueOf(timeComponents[1]);
// }
// else if (timeComponents.length == 1) {
// seconds += Integer.valueOf(timeComponents[0]);
// }
// return seconds;
// }
//
// /***
// * If the given string is shorter than the desired length, pad out the beginning of
// * the string with zeros so that the string has a length of desiredLength
// * @param numString An unpadded number string
// * @param desiredLength The desired length of the string with zeroes prepended
// * @return numString padded with leading zeros
// */
// public static String fillOutLeadingZeros(String numString, int desiredLength) {
// String result = "";
// int numZerosToAdd = desiredLength - numString.length();
// if (numZerosToAdd <= 0) {
// return numString;
// }
// else {
// for (int i = 0; i < numZerosToAdd; i++) {
// result += "0";
// }
// result += numString;
// return result;
// }
// }
//
// /***
// * Make a time-formatted string from an integer number of seconds
// */
// public static String createTimeString(int seconds) {
// int hours = seconds/3600;
// int minutes = (seconds % 3600)/60;
// seconds = seconds % 60;
// String result;
// if (hours != 0) {
// result = String.valueOf(hours) + ":"
// + fillOutLeadingZeros(String.valueOf(minutes),2) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else if (minutes != 0) {
// result = String.valueOf(minutes) + ":"
// + fillOutLeadingZeros(String.valueOf(seconds),2);
// }
// else {
// result = "0:" + fillOutLeadingZeros(String.valueOf(seconds), 2);
// }
// return result;
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/components/ButtonEditText.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.TimeStringHelper;
mEditText.setRawInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME);
}
else {
mEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}
if (mHint != null) {
mEditText.setHint(mHint);
}
else {
refreshEditTextWithUnit();
}
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (mUpdateNumberAfterTextChanged) {
String text = mEditText.getText().toString();
try {
if (!mIsTime) {
mNumber = Float.valueOf(text);
}
else { | mNumber = TimeStringHelper.parseTimeString(text); |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/SortedDateStringList.java
// public class SortedDateStringList {
// ArrayList<Date> sortedDates = new ArrayList<>(4);
// DateFormat dateFormat;
// Boolean mSorted = false;
//
// public SortedDateStringList(DateFormat dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// public boolean isEmpty() {
// return sortedDates.size() == 0;
// }
//
// public boolean add(Date date) {
// if (this.contains(date)) {
// return false;
// }
// else {
// sortedDates.add(date);
// mSorted = false;
// return true;
// }
// /*int size = sortedDates.size();
// Date d1, d2;
//
// if (size == 1) {
// d1 = sortedDates.get(0);
// if (d1.compareTo(date) > 0) {
// sortedDates.add(date);
// } else {
// sortedDates.add(0, date);
// }
// return true;
// } else if (size > 1) {
// for (int i = 0; i < sortedDates.size() - 1; i++) {
// d1 = sortedDates.get(i);
// d2 = sortedDates.get(i + 1);
// if (d1.compareTo(date) > 0 && d2.compareTo(date) < 0) {
// sortedDates.add(i + 1, date);
// return true;
// }
// }
// }
// sortedDates.add(date);
// return true;*/
// }
//
// public String getDateString(int i) {
// if (!mSorted) {
// Collections.sort(sortedDates, new Comparator<Date>() {
// @Override
// public int compare(Date date, Date d2) {
// return (int)(d2.getTime() - date.getTime())/(86400);
// }
// });
// mSorted = true;
// }
// return dateFormat.format(sortedDates.get(i));
// }
//
// public boolean contains(Date date) {
// String newDateString = dateFormat.format(date);
// for (Date d : sortedDates) {
// if (newDateString.equals(dateFormat.format(d))) {
// return true;
// }
// }
// return false;
// }
// }
| import android.util.Pair;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.SortedDateStringList; | package edu.umn.paull011.evolveworkoutlogger.data_structures;
/**
* A class for holding statistics about a routine
*
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStats {
private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
private HashMap<String, String> mNotes; | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/SortedDateStringList.java
// public class SortedDateStringList {
// ArrayList<Date> sortedDates = new ArrayList<>(4);
// DateFormat dateFormat;
// Boolean mSorted = false;
//
// public SortedDateStringList(DateFormat dateFormat) {
// this.dateFormat = dateFormat;
// }
//
// public boolean isEmpty() {
// return sortedDates.size() == 0;
// }
//
// public boolean add(Date date) {
// if (this.contains(date)) {
// return false;
// }
// else {
// sortedDates.add(date);
// mSorted = false;
// return true;
// }
// /*int size = sortedDates.size();
// Date d1, d2;
//
// if (size == 1) {
// d1 = sortedDates.get(0);
// if (d1.compareTo(date) > 0) {
// sortedDates.add(date);
// } else {
// sortedDates.add(0, date);
// }
// return true;
// } else if (size > 1) {
// for (int i = 0; i < sortedDates.size() - 1; i++) {
// d1 = sortedDates.get(i);
// d2 = sortedDates.get(i + 1);
// if (d1.compareTo(date) > 0 && d2.compareTo(date) < 0) {
// sortedDates.add(i + 1, date);
// return true;
// }
// }
// }
// sortedDates.add(date);
// return true;*/
// }
//
// public String getDateString(int i) {
// if (!mSorted) {
// Collections.sort(sortedDates, new Comparator<Date>() {
// @Override
// public int compare(Date date, Date d2) {
// return (int)(d2.getTime() - date.getTime())/(86400);
// }
// });
// mSorted = true;
// }
// return dateFormat.format(sortedDates.get(i));
// }
//
// public boolean contains(Date date) {
// String newDateString = dateFormat.format(date);
// for (Date d : sortedDates) {
// if (newDateString.equals(dateFormat.format(d))) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
import android.util.Pair;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import edu.umn.paull011.evolveworkoutlogger.helper_classes.SortedDateStringList;
package edu.umn.paull011.evolveworkoutlogger.data_structures;
/**
* A class for holding statistics about a routine
*
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStats {
private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
private HashMap<String, String> mNotes; | private SortedDateStringList mSortedDates; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineStatsDataHolder.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Routine.java
// public class Routine {
//
// // Private
// private String mName;
// private String mDescription;
// private ArrayList<Exercise> mExerciseList;
// private static final String TAG = Routine.class.getSimpleName();
//
//
// // Public
// public Routine(){
// this.mName = "";
// mExerciseList = new ArrayList<>();
// }
// public Routine(String name){
// this.mName = name;
// mExerciseList = new ArrayList<>();
// }
//
//
// public String getName() {
// return mName;
// }
//
// public String getDescription() {
// return mDescription;
// }
//
//
// public void setName(String name) {
// mName = name;
// }
//
//
// public void setDescription(String description) {
// mDescription = description;
// }
//
//
// public void addExercise(Exercise e){
// mExerciseList.add(e);
// }
//
//
// public void removeExercise(int index){
// mExerciseList.remove(index);
// }
//
//
// public Exercise getExercise(int index){
// return mExerciseList.get(index);
// }
//
//
// public int getNumExercises(){
// return mExerciseList.size();
// }
//
//
// public RoutineSession createNewRoutineSession(){
// return new RoutineSession(this, true);
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
| import edu.umn.paull011.evolveworkoutlogger.data_structures.Routine;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats; | package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* A static data holder for the View Routine activity
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStatsDataHolder {
private static final RoutineStatsDataHolder instance = new RoutineStatsDataHolder(); | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Routine.java
// public class Routine {
//
// // Private
// private String mName;
// private String mDescription;
// private ArrayList<Exercise> mExerciseList;
// private static final String TAG = Routine.class.getSimpleName();
//
//
// // Public
// public Routine(){
// this.mName = "";
// mExerciseList = new ArrayList<>();
// }
// public Routine(String name){
// this.mName = name;
// mExerciseList = new ArrayList<>();
// }
//
//
// public String getName() {
// return mName;
// }
//
// public String getDescription() {
// return mDescription;
// }
//
//
// public void setName(String name) {
// mName = name;
// }
//
//
// public void setDescription(String description) {
// mDescription = description;
// }
//
//
// public void addExercise(Exercise e){
// mExerciseList.add(e);
// }
//
//
// public void removeExercise(int index){
// mExerciseList.remove(index);
// }
//
//
// public Exercise getExercise(int index){
// return mExerciseList.get(index);
// }
//
//
// public int getNumExercises(){
// return mExerciseList.size();
// }
//
//
// public RoutineSession createNewRoutineSession(){
// return new RoutineSession(this, true);
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineStatsDataHolder.java
import edu.umn.paull011.evolveworkoutlogger.data_structures.Routine;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* A static data holder for the View Routine activity
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStatsDataHolder {
private static final RoutineStatsDataHolder instance = new RoutineStatsDataHolder(); | private Routine mRoutine; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineStatsDataHolder.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Routine.java
// public class Routine {
//
// // Private
// private String mName;
// private String mDescription;
// private ArrayList<Exercise> mExerciseList;
// private static final String TAG = Routine.class.getSimpleName();
//
//
// // Public
// public Routine(){
// this.mName = "";
// mExerciseList = new ArrayList<>();
// }
// public Routine(String name){
// this.mName = name;
// mExerciseList = new ArrayList<>();
// }
//
//
// public String getName() {
// return mName;
// }
//
// public String getDescription() {
// return mDescription;
// }
//
//
// public void setName(String name) {
// mName = name;
// }
//
//
// public void setDescription(String description) {
// mDescription = description;
// }
//
//
// public void addExercise(Exercise e){
// mExerciseList.add(e);
// }
//
//
// public void removeExercise(int index){
// mExerciseList.remove(index);
// }
//
//
// public Exercise getExercise(int index){
// return mExerciseList.get(index);
// }
//
//
// public int getNumExercises(){
// return mExerciseList.size();
// }
//
//
// public RoutineSession createNewRoutineSession(){
// return new RoutineSession(this, true);
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
| import edu.umn.paull011.evolveworkoutlogger.data_structures.Routine;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats; | package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* A static data holder for the View Routine activity
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStatsDataHolder {
private static final RoutineStatsDataHolder instance = new RoutineStatsDataHolder();
private Routine mRoutine; | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/Routine.java
// public class Routine {
//
// // Private
// private String mName;
// private String mDescription;
// private ArrayList<Exercise> mExerciseList;
// private static final String TAG = Routine.class.getSimpleName();
//
//
// // Public
// public Routine(){
// this.mName = "";
// mExerciseList = new ArrayList<>();
// }
// public Routine(String name){
// this.mName = name;
// mExerciseList = new ArrayList<>();
// }
//
//
// public String getName() {
// return mName;
// }
//
// public String getDescription() {
// return mDescription;
// }
//
//
// public void setName(String name) {
// mName = name;
// }
//
//
// public void setDescription(String description) {
// mDescription = description;
// }
//
//
// public void addExercise(Exercise e){
// mExerciseList.add(e);
// }
//
//
// public void removeExercise(int index){
// mExerciseList.remove(index);
// }
//
//
// public Exercise getExercise(int index){
// return mExerciseList.get(index);
// }
//
//
// public int getNumExercises(){
// return mExerciseList.size();
// }
//
//
// public RoutineSession createNewRoutineSession(){
// return new RoutineSession(this, true);
// }
// }
//
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/data_structures/RoutineStats.java
// public class RoutineStats {
//
// private HashMap<String, ArrayList<Pair<String, Integer>>> mRoutineData;
// private HashMap<String, String> mNotes;
// private SortedDateStringList mSortedDates;
// private DateFormat mDateFormat;
//
// public RoutineStats() {
// mRoutineData = new HashMap<>(4);
// mNotes = new HashMap<>(4);
// mDateFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
// mSortedDates = new SortedDateStringList(mDateFormat);
// }
//
// public void add(Date date, String exerciseName, int setCount) {
// String dateString = mDateFormat.format(date);
// Pair<String, Integer> exerciseSetCount = new Pair<>(exerciseName, setCount);
// ArrayList<Pair<String, Integer>> setCountList;
// if (mRoutineData.containsKey(dateString)) {
// setCountList = mRoutineData.get(dateString);
// setCountList.add(exerciseSetCount);
// mSortedDates.add(date);
// }
// else {
// setCountList = new ArrayList<>(4);
// setCountList.add(exerciseSetCount);
// mRoutineData.put(dateString, setCountList);
// mSortedDates.add(date);
// }
// }
//
// public void addNote(Date date, String note) {
// String dateString = mDateFormat.format(date);
// mNotes.put(dateString, note);
// }
//
// public int getNumDates() {
// return mRoutineData.size();
// }
//
// public List<Pair<String, Integer>> getExerciseSetCounts(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mRoutineData.get(dateString);
// }
//
// public String getNote(int position) {
// String dateString = mSortedDates.getDateString(position);
// return mNotes.get(dateString);
// }
//
// public String getDateString(int position) {
// return mSortedDates.getDateString(position);
// }
//
// public String getLastPerformedDateString() {
// if (!isEmpty()) {
// return mSortedDates.getDateString(0);
// }
// else {
// return null;
// }
// }
//
// public boolean isEmpty(){
// return mRoutineData.isEmpty();
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/helper_classes/RoutineStatsDataHolder.java
import edu.umn.paull011.evolveworkoutlogger.data_structures.Routine;
import edu.umn.paull011.evolveworkoutlogger.data_structures.RoutineStats;
package edu.umn.paull011.evolveworkoutlogger.helper_classes;
/**
* A static data holder for the View Routine activity
* Created by Mitchell on 7/17/2016.
*/
public class RoutineStatsDataHolder {
private static final RoutineStatsDataHolder instance = new RoutineStatsDataHolder();
private Routine mRoutine; | private RoutineStats mRoutineStats; |
mpsonic/Evolve-Workout-Logger | app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/BaseFragment.java | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/EvolveApplication.java
// public class EvolveApplication extends Application {
// public static RefWatcher getRefWatcher(Context context) {
// EvolveApplication application = (EvolveApplication) context.getApplicationContext();
// return application.refWatcher;
// }
//
// private RefWatcher refWatcher;
//
// @Override public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
// }
// }
| import android.support.v4.app.Fragment;
import com.squareup.leakcanary.RefWatcher;
import edu.umn.paull011.evolveworkoutlogger.EvolveApplication; | package edu.umn.paull011.evolveworkoutlogger.fragments;
/**
* Base class for all fragments,
* Uses LeakCanary to check for fragment leaks
* Created by mitchell on 9/12/16.
*/
public abstract class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy(); | // Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/EvolveApplication.java
// public class EvolveApplication extends Application {
// public static RefWatcher getRefWatcher(Context context) {
// EvolveApplication application = (EvolveApplication) context.getApplicationContext();
// return application.refWatcher;
// }
//
// private RefWatcher refWatcher;
//
// @Override public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
// }
// }
// Path: app/src/main/java/edu/umn/paull011/evolveworkoutlogger/fragments/BaseFragment.java
import android.support.v4.app.Fragment;
import com.squareup.leakcanary.RefWatcher;
import edu.umn.paull011.evolveworkoutlogger.EvolveApplication;
package edu.umn.paull011.evolveworkoutlogger.fragments;
/**
* Base class for all fragments,
* Uses LeakCanary to check for fragment leaks
* Created by mitchell on 9/12/16.
*/
public abstract class BaseFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy(); | RefWatcher refWatcher = EvolveApplication.getRefWatcher(getActivity()); |
kaarelk/r4j | r4j/src/org/r4j/Raft.java | // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| this.members.addAll(m);
}
/**
* Maintenance loop. Returns the time the loop should be executed again
* @return timeout for next run or -1L for default timeout
*/
public long loop() {
switch (role) {
case CANDIDATE:
return getElection().candidateLoop();
case FOLLOWER:
return getElection().followLoop();
case LEADER:
return leaderLoop();
}
return -1L;
}
long leaderLoop() {
for (ClusterMember m : members) {
if (m.getMatchIndex() < log.getLastIndex() && System.currentTimeMillis() - m.getLastCommandReceived() > ElectionLogic.DEFAULT_STALE_MEMBER_TIMEOUT) {
logger.info("Filling backlog for: " + m + " " + m.getNextIndex() + " " + log.getLastIndex());
m.setNextIndex(log.getLastIndex());
m.getChannel().send(this, copy(log.get(m.getNextIndex())));
m.setLastcommandReceived(System.currentTimeMillis());//start backlog process only once per timeout
} else {
//ping
if (log.getLastIndex() < 0) {
| // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
// Path: r4j/src/org/r4j/Raft.java
import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
this.members.addAll(m);
}
/**
* Maintenance loop. Returns the time the loop should be executed again
* @return timeout for next run or -1L for default timeout
*/
public long loop() {
switch (role) {
case CANDIDATE:
return getElection().candidateLoop();
case FOLLOWER:
return getElection().followLoop();
case LEADER:
return leaderLoop();
}
return -1L;
}
long leaderLoop() {
for (ClusterMember m : members) {
if (m.getMatchIndex() < log.getLastIndex() && System.currentTimeMillis() - m.getLastCommandReceived() > ElectionLogic.DEFAULT_STALE_MEMBER_TIMEOUT) {
logger.info("Filling backlog for: " + m + " " + m.getNextIndex() + " " + log.getLastIndex());
m.setNextIndex(log.getLastIndex());
m.getChannel().send(this, copy(log.get(m.getNextIndex())));
m.setLastcommandReceived(System.currentTimeMillis());//start backlog process only once per timeout
} else {
//ping
if (log.getLastIndex() < 0) {
| m.getChannel().send(this, new AppendRequest(0L, 0L, term.getCurrent(), 0L, 0L, 0L, null));
|
kaarelk/r4j | r4j/src/org/r4j/Raft.java | // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| return new AppendRequest(ar.getLogTerm(), ar.getIndex(), term.getCurrent(),
ar.getPreviousIndex(), ar.getPreviousTerm(), log.getLastCommitIndex(), ar.getPayload());
}
void changeRole(Role role) {
logger.info("New role: " + role);
this.role = role;
}
public boolean append(AppendRequest entry) {
logger.info("append: " + entry);
if (role == Role.FOLLOWER) {
this.getElection().setLeaderTimestamp(System.currentTimeMillis());
return log.append(entry);
} else if (role == Role.LEADER && entry.getLeaderTerm() > term.getCurrent()) {
getElection().setFollower();
} else if (role == Role.CANDIDATE && entry.getLeaderTerm() >= term.getCurrent()) {
getElection().setFollower();
}
if (term.getCurrent() < entry.getLeaderTerm()) {
term.setCurrent(entry.getLeaderTerm());
}
return false;//TODO do we need to respond in this case?
}
public Term getTerm() {
return term;
}
| // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
// Path: r4j/src/org/r4j/Raft.java
import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return new AppendRequest(ar.getLogTerm(), ar.getIndex(), term.getCurrent(),
ar.getPreviousIndex(), ar.getPreviousTerm(), log.getLastCommitIndex(), ar.getPayload());
}
void changeRole(Role role) {
logger.info("New role: " + role);
this.role = role;
}
public boolean append(AppendRequest entry) {
logger.info("append: " + entry);
if (role == Role.FOLLOWER) {
this.getElection().setLeaderTimestamp(System.currentTimeMillis());
return log.append(entry);
} else if (role == Role.LEADER && entry.getLeaderTerm() > term.getCurrent()) {
getElection().setFollower();
} else if (role == Role.CANDIDATE && entry.getLeaderTerm() >= term.getCurrent()) {
getElection().setFollower();
}
if (term.getCurrent() < entry.getLeaderTerm()) {
term.setCurrent(entry.getLeaderTerm());
}
return false;//TODO do we need to respond in this case?
}
public Term getTerm() {
return term;
}
| public void handleClientRequest(MessageChannel channel, Object event) {
|
kaarelk/r4j | r4j/src/org/r4j/Raft.java | // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| public Term getTerm() {
return term;
}
public void handleClientRequest(MessageChannel channel, Object event) {
if (role == Role.LEADER) {
AppendRequest req = new AppendRequest(term.getCurrent(),
log.getLastIndex()+1,
term.getCurrent(),
log.getLastIndex(),
log.getLastTerm(),
log.getLastCommitIndex(),
event,
channel);
if (!log.append(req)) {
//problem with statemachine
throw new IllegalStateException("Log didn't accept new entry: " + req + ": " + log);
}
for (ClusterMember m : members) {
if (m.getNextIndex() == req.getIndex()) {
m.setNextIndex(m.getNextIndex()+1);//increment optimistically to minimize retries
m.getChannel().send(this, req);
}
}
} else {
throw new NotLeaderException();//TODO add redirect leader
}
}
| // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/AppendResponse.java
// public class AppendResponse {
//
// private long currentTerm;
//
// private boolean success;
//
// private long entryIndex;
//
// private long entryTerm;
//
//
// public AppendResponse(long currentTerm, boolean success, long entryIndex,
// long entryTerm) {
// super();
// this.currentTerm = currentTerm;
// this.success = success;
// this.entryIndex = entryIndex;
// this.entryTerm = entryTerm;
// }
//
// public AppendResponse() {
// super();
// }
//
// public long getCurrentTerm() {
// return currentTerm;
// }
//
// public void setCurrentTerm(long term) {
// this.currentTerm = term;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public long getEntryIndex() {
// return entryIndex;
// }
//
// public long getEntryTerm() {
// return entryTerm;
// }
//
// @Override
// public String toString() {
// return "AppendResponse [currentTerm=" + currentTerm + ", success="
// + success + ", entryIndex=" + entryIndex + ", entryTerm="
// + entryTerm + "]";
// }
//
//
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/MessageChannel.java
// public interface MessageChannel {
//
// public void send(Raft source, Object o);
//
// }
// Path: r4j/src/org/r4j/Raft.java
import java.util.ArrayList;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.AppendResponse;
import org.r4j.protocol.MessageChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public Term getTerm() {
return term;
}
public void handleClientRequest(MessageChannel channel, Object event) {
if (role == Role.LEADER) {
AppendRequest req = new AppendRequest(term.getCurrent(),
log.getLastIndex()+1,
term.getCurrent(),
log.getLastIndex(),
log.getLastTerm(),
log.getLastCommitIndex(),
event,
channel);
if (!log.append(req)) {
//problem with statemachine
throw new IllegalStateException("Log didn't accept new entry: " + req + ": " + log);
}
for (ClusterMember m : members) {
if (m.getNextIndex() == req.getIndex()) {
m.setNextIndex(m.getNextIndex()+1);//increment optimistically to minimize retries
m.getChannel().send(this, req);
}
}
} else {
throw new NotLeaderException();//TODO add redirect leader
}
}
| public void handleResponse(ClusterMember member, AppendResponse event) {
|
kaarelk/r4j | r4j/src/org/r4j/protocol/RaftEvent.java | // Path: r4j/src/org/r4j/ClusterMember.java
// public interface ClusterMember {
//
// public MessageChannel getChannel();
//
// public long getNextIndex();
//
// public void setNextIndex(long index);
//
// public long getMatchIndex();
//
// public void setMatchIndex(long matchIndex);
//
// public long getLastCommandReceived();
//
// public void setLastcommandReceived(long time);
// }
| import org.r4j.ClusterMember;
| package org.r4j.protocol;
public class RaftEvent {
public enum EventType {
APPEND,
APPEND_RESPONSE,
REQUEST_VOTE,
VOTE_GRANTED,
LOOP,
CLIENT_REQUEST,
;
}
| // Path: r4j/src/org/r4j/ClusterMember.java
// public interface ClusterMember {
//
// public MessageChannel getChannel();
//
// public long getNextIndex();
//
// public void setNextIndex(long index);
//
// public long getMatchIndex();
//
// public void setMatchIndex(long matchIndex);
//
// public long getLastCommandReceived();
//
// public void setLastcommandReceived(long time);
// }
// Path: r4j/src/org/r4j/protocol/RaftEvent.java
import org.r4j.ClusterMember;
package org.r4j.protocol;
public class RaftEvent {
public enum EventType {
APPEND,
APPEND_RESPONSE,
REQUEST_VOTE,
VOTE_GRANTED,
LOOP,
CLIENT_REQUEST,
;
}
| private ClusterMember source;
|
kaarelk/r4j | restful-r4j/src/org/r4j/rest/cluster/conf/LogReaderTest.java | // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
| package org.r4j.rest.cluster.conf;
public class LogReaderTest {
@Test
public void test() throws JsonProcessingException, IOException {
ObjectMapper om = new ObjectMapper();
| // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
// Path: restful-r4j/src/org/r4j/rest/cluster/conf/LogReaderTest.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.r4j.protocol.AppendRequest;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
package org.r4j.rest.cluster.conf;
public class LogReaderTest {
@Test
public void test() throws JsonProcessingException, IOException {
ObjectMapper om = new ObjectMapper();
| MappingIterator<AppendRequest> iter = om.reader(AppendRequest.class).readValues(new File("test1.log"));
|
kaarelk/r4j | r4j/src/org/r4j/ElectionLogic.java | // Path: r4j/src/org/r4j/protocol/RequestForVote.java
// public class RequestForVote {
//
// private long term;
//
// private long lastLogIndex;
//
// private long lastLogTerm;
//
// public RequestForVote(long term, long lastLogIndex, long lastLogTerm) {
// super();
// this.term = term;
// this.lastLogIndex = lastLogIndex;
// this.lastLogTerm = lastLogTerm;
// }
//
// public RequestForVote() {
// super();
// }
//
// public long getTerm() {
// return term;
// }
//
// public void setTerm(long term) {
// this.term = term;
// }
//
// public long getLastLogIndex() {
// return lastLogIndex;
// }
//
// public void setLastLogIndex(long lastLogIndex) {
// this.lastLogIndex = lastLogIndex;
// }
//
// public long getLastLogTerm() {
// return lastLogTerm;
// }
//
// public void setLastLogTerm(long lastLogTerm) {
// this.lastLogTerm = lastLogTerm;
// }
//
// @Override
// public String toString() {
// return "RequestForVote [term=" + term + ", lastLogIndex="
// + lastLogIndex + ", lastLogTerm=" + lastLogTerm + "]";
// }
//
// }
//
// Path: r4j/src/org/r4j/protocol/VoteGranted.java
// public class VoteGranted {
//
// private long term;
//
// public VoteGranted() {
// super();
// }
//
// public VoteGranted(long term) {
// super();
// this.term = term;
// }
//
// public long getTerm() {
// return term;
// }
//
// }
| import java.util.Random;
import org.r4j.protocol.RequestForVote;
import org.r4j.protocol.VoteGranted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| package org.r4j;
public class ElectionLogic {
public static long DEFAULT_LEADER_TIMEOUT = 10000L;
public static long DEFAULT_ELECTION_TIMEOUT = 10000L;
public static long PING_LOOP = 1000L;
public static long DEFAULT_STALE_MEMBER_TIMEOUT = DEFAULT_LEADER_TIMEOUT;
private Random random = new Random();
private Logger logger = LoggerFactory.getLogger(Raft.class);
private Election election;
protected long votedForTerm = -1;
private long leaderTimestamp = System.currentTimeMillis();
private long leaderTimeout = DEFAULT_LEADER_TIMEOUT;
private long electionTime = -1L;
private long electionEnd = -1L;
private Raft raft;
public ElectionLogic(Raft raft) {
super();
this.raft = raft;
}
| // Path: r4j/src/org/r4j/protocol/RequestForVote.java
// public class RequestForVote {
//
// private long term;
//
// private long lastLogIndex;
//
// private long lastLogTerm;
//
// public RequestForVote(long term, long lastLogIndex, long lastLogTerm) {
// super();
// this.term = term;
// this.lastLogIndex = lastLogIndex;
// this.lastLogTerm = lastLogTerm;
// }
//
// public RequestForVote() {
// super();
// }
//
// public long getTerm() {
// return term;
// }
//
// public void setTerm(long term) {
// this.term = term;
// }
//
// public long getLastLogIndex() {
// return lastLogIndex;
// }
//
// public void setLastLogIndex(long lastLogIndex) {
// this.lastLogIndex = lastLogIndex;
// }
//
// public long getLastLogTerm() {
// return lastLogTerm;
// }
//
// public void setLastLogTerm(long lastLogTerm) {
// this.lastLogTerm = lastLogTerm;
// }
//
// @Override
// public String toString() {
// return "RequestForVote [term=" + term + ", lastLogIndex="
// + lastLogIndex + ", lastLogTerm=" + lastLogTerm + "]";
// }
//
// }
//
// Path: r4j/src/org/r4j/protocol/VoteGranted.java
// public class VoteGranted {
//
// private long term;
//
// public VoteGranted() {
// super();
// }
//
// public VoteGranted(long term) {
// super();
// this.term = term;
// }
//
// public long getTerm() {
// return term;
// }
//
// }
// Path: r4j/src/org/r4j/ElectionLogic.java
import java.util.Random;
import org.r4j.protocol.RequestForVote;
import org.r4j.protocol.VoteGranted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.r4j;
public class ElectionLogic {
public static long DEFAULT_LEADER_TIMEOUT = 10000L;
public static long DEFAULT_ELECTION_TIMEOUT = 10000L;
public static long PING_LOOP = 1000L;
public static long DEFAULT_STALE_MEMBER_TIMEOUT = DEFAULT_LEADER_TIMEOUT;
private Random random = new Random();
private Logger logger = LoggerFactory.getLogger(Raft.class);
private Election election;
protected long votedForTerm = -1;
private long leaderTimestamp = System.currentTimeMillis();
private long leaderTimeout = DEFAULT_LEADER_TIMEOUT;
private long electionTime = -1L;
private long electionEnd = -1L;
private Raft raft;
public ElectionLogic(Raft raft) {
super();
this.raft = raft;
}
| public void voteReceived(VoteGranted vote) {
|
kaarelk/r4j | r4j/src/org/r4j/ElectionLogic.java | // Path: r4j/src/org/r4j/protocol/RequestForVote.java
// public class RequestForVote {
//
// private long term;
//
// private long lastLogIndex;
//
// private long lastLogTerm;
//
// public RequestForVote(long term, long lastLogIndex, long lastLogTerm) {
// super();
// this.term = term;
// this.lastLogIndex = lastLogIndex;
// this.lastLogTerm = lastLogTerm;
// }
//
// public RequestForVote() {
// super();
// }
//
// public long getTerm() {
// return term;
// }
//
// public void setTerm(long term) {
// this.term = term;
// }
//
// public long getLastLogIndex() {
// return lastLogIndex;
// }
//
// public void setLastLogIndex(long lastLogIndex) {
// this.lastLogIndex = lastLogIndex;
// }
//
// public long getLastLogTerm() {
// return lastLogTerm;
// }
//
// public void setLastLogTerm(long lastLogTerm) {
// this.lastLogTerm = lastLogTerm;
// }
//
// @Override
// public String toString() {
// return "RequestForVote [term=" + term + ", lastLogIndex="
// + lastLogIndex + ", lastLogTerm=" + lastLogTerm + "]";
// }
//
// }
//
// Path: r4j/src/org/r4j/protocol/VoteGranted.java
// public class VoteGranted {
//
// private long term;
//
// public VoteGranted() {
// super();
// }
//
// public VoteGranted(long term) {
// super();
// this.term = term;
// }
//
// public long getTerm() {
// return term;
// }
//
// }
| import java.util.Random;
import org.r4j.protocol.RequestForVote;
import org.r4j.protocol.VoteGranted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| for (ClusterMember m : raft.getMembers()) {
m.setNextIndex(raft.getLog().getLastIndex() + 1);
m.setMatchIndex(0L);
m.setLastcommandReceived(System.currentTimeMillis());//new leader didn't receive any command, don't fill backlog write away
}
raft.leaderLoop();//starts sending log
}
public long followLoop() {
if (electionTime > 0L) {
return tryStartElection();
}
long time = System.currentTimeMillis();
if (leaderTimeout < (time - leaderTimestamp)) {
raft.changeRole(Role.CANDIDATE);
electionEnd = -1L;
long rdiff = random.nextInt((int)DEFAULT_ELECTION_TIMEOUT) + 1;
setElectionTime(time + rdiff);
return electionTime - time;
}
return -1L;
}
private long tryStartElection() {
long time = System.currentTimeMillis();
if (electionTime <= time) {
setElectionTime(-1L);
this.raft.getTerm().newTerm();
this.election = new Election(raft.getMembers().size() + 1, this.raft.getTerm().getCurrent());
for (ClusterMember m : raft.getMembers()) {
| // Path: r4j/src/org/r4j/protocol/RequestForVote.java
// public class RequestForVote {
//
// private long term;
//
// private long lastLogIndex;
//
// private long lastLogTerm;
//
// public RequestForVote(long term, long lastLogIndex, long lastLogTerm) {
// super();
// this.term = term;
// this.lastLogIndex = lastLogIndex;
// this.lastLogTerm = lastLogTerm;
// }
//
// public RequestForVote() {
// super();
// }
//
// public long getTerm() {
// return term;
// }
//
// public void setTerm(long term) {
// this.term = term;
// }
//
// public long getLastLogIndex() {
// return lastLogIndex;
// }
//
// public void setLastLogIndex(long lastLogIndex) {
// this.lastLogIndex = lastLogIndex;
// }
//
// public long getLastLogTerm() {
// return lastLogTerm;
// }
//
// public void setLastLogTerm(long lastLogTerm) {
// this.lastLogTerm = lastLogTerm;
// }
//
// @Override
// public String toString() {
// return "RequestForVote [term=" + term + ", lastLogIndex="
// + lastLogIndex + ", lastLogTerm=" + lastLogTerm + "]";
// }
//
// }
//
// Path: r4j/src/org/r4j/protocol/VoteGranted.java
// public class VoteGranted {
//
// private long term;
//
// public VoteGranted() {
// super();
// }
//
// public VoteGranted(long term) {
// super();
// this.term = term;
// }
//
// public long getTerm() {
// return term;
// }
//
// }
// Path: r4j/src/org/r4j/ElectionLogic.java
import java.util.Random;
import org.r4j.protocol.RequestForVote;
import org.r4j.protocol.VoteGranted;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
for (ClusterMember m : raft.getMembers()) {
m.setNextIndex(raft.getLog().getLastIndex() + 1);
m.setMatchIndex(0L);
m.setLastcommandReceived(System.currentTimeMillis());//new leader didn't receive any command, don't fill backlog write away
}
raft.leaderLoop();//starts sending log
}
public long followLoop() {
if (electionTime > 0L) {
return tryStartElection();
}
long time = System.currentTimeMillis();
if (leaderTimeout < (time - leaderTimestamp)) {
raft.changeRole(Role.CANDIDATE);
electionEnd = -1L;
long rdiff = random.nextInt((int)DEFAULT_ELECTION_TIMEOUT) + 1;
setElectionTime(time + rdiff);
return electionTime - time;
}
return -1L;
}
private long tryStartElection() {
long time = System.currentTimeMillis();
if (electionTime <= time) {
setElectionTime(-1L);
this.raft.getTerm().newTerm();
this.election = new Election(raft.getMembers().size() + 1, this.raft.getTerm().getCurrent());
for (ClusterMember m : raft.getMembers()) {
| m.getChannel().send(raft, new RequestForVote(this.raft.getTerm().getCurrent(), raft.getLog().getLastIndex(), raft.getLog().getLastTerm()));
|
kaarelk/r4j | r4j/src/org/r4j/example/RespondingCommitHandler.java | // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
| import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientResponse;
| package org.r4j.example;
public class RespondingCommitHandler implements CommitHandler {
@Override
| // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
// Path: r4j/src/org/r4j/example/RespondingCommitHandler.java
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientResponse;
package org.r4j.example;
public class RespondingCommitHandler implements CommitHandler {
@Override
| public void commit(AppendRequest entry) {
|
kaarelk/r4j | r4j/src/org/r4j/example/RespondingCommitHandler.java | // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
| import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientResponse;
| package org.r4j.example;
public class RespondingCommitHandler implements CommitHandler {
@Override
public void commit(AppendRequest entry) {
Object o = commitImpl(entry);
if (entry.getClientChannel() != null) {
entry.getClientChannel().send(null, o);
}
}
protected Object commitImpl(AppendRequest entry) {
| // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
// Path: r4j/src/org/r4j/example/RespondingCommitHandler.java
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientResponse;
package org.r4j.example;
public class RespondingCommitHandler implements CommitHandler {
@Override
public void commit(AppendRequest entry) {
Object o = commitImpl(entry);
if (entry.getClientChannel() != null) {
entry.getClientChannel().send(null, o);
}
}
protected Object commitImpl(AppendRequest entry) {
| return new ClientResponse(0, null);
|
kaarelk/r4j | restful-r4j/src/org/r4j/rest/cluster/Commits.java | // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientRequest.java
// public class ClientRequest {
//
// /**
// * Payload of object, including reference to client MessageChannel
// */
// private Object payload;
//
//
// public ClientRequest() {
// super();
// }
//
// public ClientRequest(Object payload) {
// super();
// this.payload = payload;
// }
//
// public Object getPayload() {
// return payload;
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientRequest;
import org.r4j.protocol.ClientResponse;
| package org.r4j.rest.cluster;
public class Commits implements CommitHandler {
//replace with leveldb
private Map<String, String> map = new HashMap<>();
@Override
| // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientRequest.java
// public class ClientRequest {
//
// /**
// * Payload of object, including reference to client MessageChannel
// */
// private Object payload;
//
//
// public ClientRequest() {
// super();
// }
//
// public ClientRequest(Object payload) {
// super();
// this.payload = payload;
// }
//
// public Object getPayload() {
// return payload;
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
// Path: restful-r4j/src/org/r4j/rest/cluster/Commits.java
import java.util.HashMap;
import java.util.Map;
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientRequest;
import org.r4j.protocol.ClientResponse;
package org.r4j.rest.cluster;
public class Commits implements CommitHandler {
//replace with leveldb
private Map<String, String> map = new HashMap<>();
@Override
| public void commit(AppendRequest entry) {
|
kaarelk/r4j | restful-r4j/src/org/r4j/rest/cluster/Commits.java | // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientRequest.java
// public class ClientRequest {
//
// /**
// * Payload of object, including reference to client MessageChannel
// */
// private Object payload;
//
//
// public ClientRequest() {
// super();
// }
//
// public ClientRequest(Object payload) {
// super();
// this.payload = payload;
// }
//
// public Object getPayload() {
// return payload;
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientRequest;
import org.r4j.protocol.ClientResponse;
| package org.r4j.rest.cluster;
public class Commits implements CommitHandler {
//replace with leveldb
private Map<String, String> map = new HashMap<>();
@Override
public void commit(AppendRequest entry) {
Object o = entry.getPayload();
if (o instanceof Put) {
Put p = (Put)o;
map.put(p.getKey(), p.getValue());
if (entry.getClientChannel() != null) {
| // Path: r4j/src/org/r4j/CommitHandler.java
// public interface CommitHandler {
//
// /**
// * Commits the entry. Should NEVER fail. Retry should be handled by CommitHandler implementation
// * @param entry
// */
// public void commit(AppendRequest entry);
//
// public void reject(AppendRequest entry);
// }
//
// Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientRequest.java
// public class ClientRequest {
//
// /**
// * Payload of object, including reference to client MessageChannel
// */
// private Object payload;
//
//
// public ClientRequest() {
// super();
// }
//
// public ClientRequest(Object payload) {
// super();
// this.payload = payload;
// }
//
// public Object getPayload() {
// return payload;
// }
//
//
// }
//
// Path: r4j/src/org/r4j/protocol/ClientResponse.java
// public class ClientResponse {
//
// private int errCode;
//
// private Object payload;
//
// public ClientResponse(int errCode, Object payload) {
// super();
// this.errCode = errCode;
// this.payload = payload;
// }
//
// public ClientResponse() {
// super();
// }
//
// public int getErrCode() {
// return errCode;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// return "ClientResponse [errCode=" + errCode + ", payload=" + payload
// + "]";
// }
//
// }
// Path: restful-r4j/src/org/r4j/rest/cluster/Commits.java
import java.util.HashMap;
import java.util.Map;
import org.r4j.CommitHandler;
import org.r4j.protocol.AppendRequest;
import org.r4j.protocol.ClientRequest;
import org.r4j.protocol.ClientResponse;
package org.r4j.rest.cluster;
public class Commits implements CommitHandler {
//replace with leveldb
private Map<String, String> map = new HashMap<>();
@Override
public void commit(AppendRequest entry) {
Object o = entry.getPayload();
if (o instanceof Put) {
Put p = (Put)o;
map.put(p.getKey(), p.getValue());
if (entry.getClientChannel() != null) {
| entry.getClientChannel().send(null, new ClientResponse(0, ""));
|
kaarelk/r4j | r4j/src/org/r4j/LogImpl.java | // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.r4j.protocol.AppendRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| package org.r4j;
public class LogImpl implements Log {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final long LOG_START = 0;
/** marker for log start - used for compacting log */
protected long logStartIndex = 0;
| // Path: r4j/src/org/r4j/protocol/AppendRequest.java
// public class AppendRequest {
//
// private long index;
// private long leaderTerm;
// private long logTerm;
// private long previousIndex;
// private long previousTerm;
// private long commitIndex;
// private Object payload;
// private transient MessageChannel clientChannel;
//
// public AppendRequest() {
// super();
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// }
//
// public AppendRequest(long logTerm, long index, long leaderTerm, long previousIndex,
// long previousTerm, long commitIndex, Object payload,
// MessageChannel clientChannel) {
// super();
// this.logTerm = logTerm;
// this.index = index;
// this.leaderTerm = leaderTerm;
// this.previousIndex = previousIndex;
// this.previousTerm = previousTerm;
// this.commitIndex = commitIndex;
// this.payload = payload;
// this.clientChannel = clientChannel;
// }
//
// public long getIndex() {
// return index;
// }
//
// public long getLeaderTerm() {
// return leaderTerm;
// }
//
// public long getLogTerm() {
// return logTerm;
// }
//
// public long getPreviousIndex() {
// return previousIndex;
// }
//
// public long getPreviousTerm() {
// return previousTerm;
// }
//
// public long getCommitIndex() {
// return commitIndex;
// }
//
// public Object getPayload() {
// return payload;
// }
//
// @JsonIgnore
// public MessageChannel getClientChannel() {
// return clientChannel;
// }
//
// @Override
// public String toString() {
// return "AppendRequest [index=" + index + ", term=" + leaderTerm
// + ", previousIndex=" + previousIndex + ", previousTerm="
// + previousTerm + ", commitIndex=" + commitIndex + ", "
// + (payload != null ? "payload=" + payload : "") + "]";
// }
//
//
// }
// Path: r4j/src/org/r4j/LogImpl.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.r4j.protocol.AppendRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package org.r4j;
public class LogImpl implements Log {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final long LOG_START = 0;
/** marker for log start - used for compacting log */
protected long logStartIndex = 0;
| protected List<AppendRequest> log = new ArrayList<AppendRequest>();
|
xinthink/react-native-material-kit | example/android/app/src/main/java/com/github/xinthink/rnmk/demo/MainApplication.java | // Path: android/src/main/java/com/github/xinthink/rnmk/ReactMaterialKitPackage.java
// public class ReactMaterialKitPackage implements ReactPackage {
//
// @Override
// public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
// return Collections.emptyList();
// }
//
// // Deprecated RN 0.47
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
//
// @Override
// public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
// return Arrays.<ViewManager>asList(
// new MKTouchableManager(),
// new MKSpinnerManager(),
// new TickViewManager()
// );
// }
// }
| import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import com.github.xinthink.rnmk.ReactMaterialKitPackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List; | package com.github.xinthink.rnmk.demo;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage()); | // Path: android/src/main/java/com/github/xinthink/rnmk/ReactMaterialKitPackage.java
// public class ReactMaterialKitPackage implements ReactPackage {
//
// @Override
// public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
// return Collections.emptyList();
// }
//
// // Deprecated RN 0.47
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
//
// @Override
// public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
// return Arrays.<ViewManager>asList(
// new MKTouchableManager(),
// new MKSpinnerManager(),
// new TickViewManager()
// );
// }
// }
// Path: example/android/app/src/main/java/com/github/xinthink/rnmk/demo/MainApplication.java
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import com.github.xinthink.rnmk.ReactMaterialKitPackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
package com.github.xinthink.rnmk.demo;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage()); | packages.add(new ReactMaterialKitPackage()); |
tavianator/sangria | sangria-listbinder/src/test/java/com/tavianator/sangria/listbinder/ListBinderTest.java | // Path: sangria-core/src/main/java/com/tavianator/sangria/core/TypeLiterals.java
// public class TypeLiterals {
// private TypeLiterals() {
// // Not for instantiating
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<List<T>> listOf(Class<T> type) {
// return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<List<T>> listOf(TypeLiteral<T> type) {
// return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Set<T>> setOf(Class<T> type) {
// return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Set<T>> setOf(TypeLiteral<T> type) {
// return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, TypeLiteral<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, Class<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, TypeLiteral<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Provider<T>> providerOf(Class<T> type) {
// // Can't use Types.providerOf() because we want to stick to JSR-330 Providers
// return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Provider<T>> providerOf(TypeLiteral<T> type) {
// // Can't use Types.providerOf() because we want to stick to JSR-330 Providers
// return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type.getType()));
// }
// }
| import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.tavianator.sangria.core.TypeLiterals;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.*;
import javax.inject.Provider;
import javax.inject.Qualifier;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names; | /****************************************************************************
* Sangria *
* Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.com> *
* *
* 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.tavianator.sangria.listbinder;
/**
* Tests for {@link ListBinder}.
*
* @author Tavian Barnes (tavianator@tavianator.com)
* @version 1.1
* @since 1.1
*/
public class ListBinderTest {
public @Rule ExpectedException thrown = ExpectedException.none();
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
private @interface Simple {
}
| // Path: sangria-core/src/main/java/com/tavianator/sangria/core/TypeLiterals.java
// public class TypeLiterals {
// private TypeLiterals() {
// // Not for instantiating
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<List<T>> listOf(Class<T> type) {
// return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<List<T>> listOf(TypeLiteral<T> type) {
// return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Set<T>> setOf(Class<T> type) {
// return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Set<T>> setOf(TypeLiteral<T> type) {
// return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, TypeLiteral<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, Class<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType));
// }
//
// @SuppressWarnings("unchecked")
// public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, TypeLiteral<V> valueType) {
// return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType.getType()));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Provider<T>> providerOf(Class<T> type) {
// // Can't use Types.providerOf() because we want to stick to JSR-330 Providers
// return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type));
// }
//
// @SuppressWarnings("unchecked")
// public static <T> TypeLiteral<Provider<T>> providerOf(TypeLiteral<T> type) {
// // Can't use Types.providerOf() because we want to stick to JSR-330 Providers
// return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type.getType()));
// }
// }
// Path: sangria-listbinder/src/test/java/com/tavianator/sangria/listbinder/ListBinderTest.java
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.tavianator.sangria.core.TypeLiterals;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.*;
import javax.inject.Provider;
import javax.inject.Qualifier;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
/****************************************************************************
* Sangria *
* Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.com> *
* *
* 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.tavianator.sangria.listbinder;
/**
* Tests for {@link ListBinder}.
*
* @author Tavian Barnes (tavianator@tavianator.com)
* @version 1.1
* @since 1.1
*/
public class ListBinderTest {
public @Rule ExpectedException thrown = ExpectedException.none();
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
private @interface Simple {
}
| private static final TypeLiteral<List<String>> LIST_OF_STRINGS = TypeLiterals.listOf(String.class); |
tavianator/sangria | sangria-listbinder/src/main/java/com/tavianator/sangria/listbinder/ListElement.java | // Path: sangria-core/src/main/java/com/tavianator/sangria/core/Priority.java
// public class Priority implements Comparable<Priority> {
// private static final Priority DEFAULT = new Priority(new int[0], 0);
// private static final Comparator<int[]> COMPARATOR = Ints.lexicographicalComparator();
//
// private final int[] weights;
// private final int seq;
//
// /**
// * @return The default priority, which comes before all other priorities.
// */
// public static Priority getDefault() {
// return DEFAULT;
// }
//
// /**
// * Create a {@link Priority} with the given sequence.
// *
// * @param weight The first value of the weight sequence.
// * @param weights An integer sequence. These sequences are sorted lexicographically, so {@code Priority.create(1)}
// * sorts before {@code Priority.create(1, 1)}, which sorts before {@code Priority.create(2)}.
// * @return A new {@link Priority}.
// */
// public static Priority create(int weight, int... weights) {
// int[] newWeights = new int[weights.length + 1];
// newWeights[0] = weight;
// System.arraycopy(weights, 0, newWeights, 1, weights.length);
// return new Priority(newWeights, 0);
// }
//
// private Priority(int[] weights, int seq) {
// this.weights = weights;
// this.seq = seq;
// }
//
// /**
// * @return Whether this priority originated in a call to {@link #getDefault()}.
// */
// public boolean isDefault() {
// return weights.length == 0;
// }
//
// /**
// * @return A new {@link Priority} which immediately follows this one, and which is distinct from all other
// * priorities obtained by {@link #create(int, int...)}.
// */
// public Priority next() {
// return new Priority(weights, seq + 1);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// } else if (!(obj instanceof Priority)) {
// return false;
// }
//
// Priority other = (Priority)obj;
// return Arrays.equals(weights, other.weights)
// && seq == other.seq;
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(weights) + seq;
// }
//
// @Override
// public int compareTo(Priority o) {
// return ComparisonChain.start()
// .compare(weights, o.weights, COMPARATOR)
// .compare(seq, o.seq)
// .result();
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// if (weights.length == 0) {
// builder.append("default priority");
// } else {
// builder.append("priority [");
// for (int i = 0; i < weights.length; ++i) {
// if (i != 0) {
// builder.append(", ");
// }
// builder.append(weights[i]);
// }
// builder.append("]");
// }
// if (seq != 0) {
// builder.append(" + ")
// .append(seq);
// }
// return builder.toString();
// }
// }
| import com.google.inject.Key;
import com.tavianator.sangria.core.Priority; | /****************************************************************************
* Sangria *
* Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.com> *
* *
* 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.tavianator.sangria.listbinder;
/**
* An individual element in a ListBinder.
*
* @author Tavian Barnes (tavianator@tavianator.com)
* @version 1.1
* @since 1.1
*/
class ListElement<T> implements Comparable<ListElement<T>> {
final Key<T> key; | // Path: sangria-core/src/main/java/com/tavianator/sangria/core/Priority.java
// public class Priority implements Comparable<Priority> {
// private static final Priority DEFAULT = new Priority(new int[0], 0);
// private static final Comparator<int[]> COMPARATOR = Ints.lexicographicalComparator();
//
// private final int[] weights;
// private final int seq;
//
// /**
// * @return The default priority, which comes before all other priorities.
// */
// public static Priority getDefault() {
// return DEFAULT;
// }
//
// /**
// * Create a {@link Priority} with the given sequence.
// *
// * @param weight The first value of the weight sequence.
// * @param weights An integer sequence. These sequences are sorted lexicographically, so {@code Priority.create(1)}
// * sorts before {@code Priority.create(1, 1)}, which sorts before {@code Priority.create(2)}.
// * @return A new {@link Priority}.
// */
// public static Priority create(int weight, int... weights) {
// int[] newWeights = new int[weights.length + 1];
// newWeights[0] = weight;
// System.arraycopy(weights, 0, newWeights, 1, weights.length);
// return new Priority(newWeights, 0);
// }
//
// private Priority(int[] weights, int seq) {
// this.weights = weights;
// this.seq = seq;
// }
//
// /**
// * @return Whether this priority originated in a call to {@link #getDefault()}.
// */
// public boolean isDefault() {
// return weights.length == 0;
// }
//
// /**
// * @return A new {@link Priority} which immediately follows this one, and which is distinct from all other
// * priorities obtained by {@link #create(int, int...)}.
// */
// public Priority next() {
// return new Priority(weights, seq + 1);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// } else if (!(obj instanceof Priority)) {
// return false;
// }
//
// Priority other = (Priority)obj;
// return Arrays.equals(weights, other.weights)
// && seq == other.seq;
// }
//
// @Override
// public int hashCode() {
// return Arrays.hashCode(weights) + seq;
// }
//
// @Override
// public int compareTo(Priority o) {
// return ComparisonChain.start()
// .compare(weights, o.weights, COMPARATOR)
// .compare(seq, o.seq)
// .result();
// }
//
// @Override
// public String toString() {
// StringBuilder builder = new StringBuilder();
// if (weights.length == 0) {
// builder.append("default priority");
// } else {
// builder.append("priority [");
// for (int i = 0; i < weights.length; ++i) {
// if (i != 0) {
// builder.append(", ");
// }
// builder.append(weights[i]);
// }
// builder.append("]");
// }
// if (seq != 0) {
// builder.append(" + ")
// .append(seq);
// }
// return builder.toString();
// }
// }
// Path: sangria-listbinder/src/main/java/com/tavianator/sangria/listbinder/ListElement.java
import com.google.inject.Key;
import com.tavianator.sangria.core.Priority;
/****************************************************************************
* Sangria *
* Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.com> *
* *
* 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.tavianator.sangria.listbinder;
/**
* An individual element in a ListBinder.
*
* @author Tavian Barnes (tavianator@tavianator.com)
* @version 1.1
* @since 1.1
*/
class ListElement<T> implements Comparable<ListElement<T>> {
final Key<T> key; | final Priority priority; |
tavianator/sangria | sangria-contextual/src/main/java/com/tavianator/sangria/contextual/ContextSensitiveBinder.java | // Path: sangria-core/src/main/java/com/tavianator/sangria/core/DelayedError.java
// public class DelayedError {
// private Throwable error;
// private boolean reported = false;
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param message The format string for the message.
// * @param args Arguments that will be passed to the format string.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(String, Object...)
// */
// public static DelayedError create(Binder binder, String message, Object... args) {
// return create(binder, new Message(PrettyTypes.format(message, args)));
// }
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param t The {@link Throwable} that caused this potential error.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(Throwable)
// */
// public static DelayedError create(Binder binder, Throwable t) {
// DelayedError error = new DelayedError(t);
// binder.skipSources(DelayedError.class)
// .requestInjection(error);
// return error;
// }
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param message The error message.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(Message)
// */
// public static DelayedError create(Binder binder, Message message) {
// // Using CreationException allows Guice to extract the Message and format it nicely
// return create(binder, new CreationException(ImmutableList.of(message)));
// }
//
// private DelayedError(Throwable error) {
// this.error = error;
// }
//
// /**
// * Cancel this error.
// */
// public void cancel() {
// checkState(!reported, "This error has already been reported");
// error = null;
// }
//
// @Inject
// void reportErrors(Injector injector) throws Throwable {
// reported = true;
// if (error != null) {
// throw error;
// }
// }
// }
//
// Path: sangria-core/src/main/java/com/tavianator/sangria/core/UniqueAnnotations.java
// public class UniqueAnnotations {
// private static final AtomicLong SEQUENCE = new AtomicLong();
//
// private UniqueAnnotations() {
// // Not for instantiating
// }
//
// @Retention(RetentionPolicy.RUNTIME)
// @Qualifier
// @VisibleForTesting
// @interface UniqueAnnotation {
// long value();
// }
//
// /**
// * Actual implementation of {@link UniqueAnnotation}.
// */
// @SuppressWarnings("ClassExplicitlyAnnotation")
// private static class UniqueAnnotationImpl implements UniqueAnnotation {
// private final long value;
//
// UniqueAnnotationImpl(long value) {
// this.value = value;
// }
//
// @Override
// public long value() {
// return value;
// }
//
// public Class<? extends Annotation> annotationType() {
// return UniqueAnnotation.class;
// }
//
// @Override
// public String toString() {
// return "@" + UniqueAnnotation.class.getName() + "(value=" + value + ")";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// } else if (!(obj instanceof UniqueAnnotation)) {
// return false;
// }
//
// UniqueAnnotation other = (UniqueAnnotation)obj;
// return value == other.value();
// }
//
// @Override
// public int hashCode() {
// return (127*"value".hashCode()) ^ Long.valueOf(value).hashCode();
// }
// }
//
// /**
// * @return An {@link Annotation} that will be unequal to every other annotation.
// */
// public static Annotation create() {
// return create(SEQUENCE.getAndIncrement());
// }
//
// @VisibleForTesting
// static Annotation create(long value) {
// return new UniqueAnnotationImpl(value);
// }
// }
| import java.lang.annotation.Annotation;
import java.util.*;
import javax.inject.Inject;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.ConfigurationException;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.DependencyAndSource;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.ProvisionListener;
import com.tavianator.sangria.core.DelayedError;
import com.tavianator.sangria.core.UniqueAnnotations; |
@Override
public ContextSensitiveBindingBuilder<T> annotatedWith(Annotation annotation) {
error.cancel();
return new BindingBuilder<>(Key.get(bindingKey.getTypeLiteral(), annotation));
}
@Override
public void toContextSensitiveProvider(Class<? extends ContextSensitiveProvider<? extends T>> type) {
toContextSensitiveProvider(Key.get(type));
}
@Override
public void toContextSensitiveProvider(TypeLiteral<? extends ContextSensitiveProvider<? extends T>> type) {
toContextSensitiveProvider(Key.get(type));
}
@Override
public void toContextSensitiveProvider(Key<? extends ContextSensitiveProvider<? extends T>> key) {
error.cancel();
Provider<? extends ContextSensitiveProvider<? extends T>> provider = binder.getProvider(makeUniqueLinkedKey(key));
binder.bind(bindingKey).toProvider(new ProviderKeyAdapter<>(provider, key));
binder.bindListener(new BindingMatcher(bindingKey), new Trigger(bindingKey));
}
/**
* For Binder#requireExplicitBindings() support.
*/
private <U> Key<U> makeUniqueLinkedKey(Key<U> key) { | // Path: sangria-core/src/main/java/com/tavianator/sangria/core/DelayedError.java
// public class DelayedError {
// private Throwable error;
// private boolean reported = false;
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param message The format string for the message.
// * @param args Arguments that will be passed to the format string.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(String, Object...)
// */
// public static DelayedError create(Binder binder, String message, Object... args) {
// return create(binder, new Message(PrettyTypes.format(message, args)));
// }
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param t The {@link Throwable} that caused this potential error.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(Throwable)
// */
// public static DelayedError create(Binder binder, Throwable t) {
// DelayedError error = new DelayedError(t);
// binder.skipSources(DelayedError.class)
// .requestInjection(error);
// return error;
// }
//
// /**
// * Create a {@link DelayedError}.
// *
// * @param binder The binder to attach the error to.
// * @param message The error message.
// * @return A {@link DelayedError} token that can be canceled later.
// * @see Binder#addError(Message)
// */
// public static DelayedError create(Binder binder, Message message) {
// // Using CreationException allows Guice to extract the Message and format it nicely
// return create(binder, new CreationException(ImmutableList.of(message)));
// }
//
// private DelayedError(Throwable error) {
// this.error = error;
// }
//
// /**
// * Cancel this error.
// */
// public void cancel() {
// checkState(!reported, "This error has already been reported");
// error = null;
// }
//
// @Inject
// void reportErrors(Injector injector) throws Throwable {
// reported = true;
// if (error != null) {
// throw error;
// }
// }
// }
//
// Path: sangria-core/src/main/java/com/tavianator/sangria/core/UniqueAnnotations.java
// public class UniqueAnnotations {
// private static final AtomicLong SEQUENCE = new AtomicLong();
//
// private UniqueAnnotations() {
// // Not for instantiating
// }
//
// @Retention(RetentionPolicy.RUNTIME)
// @Qualifier
// @VisibleForTesting
// @interface UniqueAnnotation {
// long value();
// }
//
// /**
// * Actual implementation of {@link UniqueAnnotation}.
// */
// @SuppressWarnings("ClassExplicitlyAnnotation")
// private static class UniqueAnnotationImpl implements UniqueAnnotation {
// private final long value;
//
// UniqueAnnotationImpl(long value) {
// this.value = value;
// }
//
// @Override
// public long value() {
// return value;
// }
//
// public Class<? extends Annotation> annotationType() {
// return UniqueAnnotation.class;
// }
//
// @Override
// public String toString() {
// return "@" + UniqueAnnotation.class.getName() + "(value=" + value + ")";
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// } else if (!(obj instanceof UniqueAnnotation)) {
// return false;
// }
//
// UniqueAnnotation other = (UniqueAnnotation)obj;
// return value == other.value();
// }
//
// @Override
// public int hashCode() {
// return (127*"value".hashCode()) ^ Long.valueOf(value).hashCode();
// }
// }
//
// /**
// * @return An {@link Annotation} that will be unequal to every other annotation.
// */
// public static Annotation create() {
// return create(SEQUENCE.getAndIncrement());
// }
//
// @VisibleForTesting
// static Annotation create(long value) {
// return new UniqueAnnotationImpl(value);
// }
// }
// Path: sangria-contextual/src/main/java/com/tavianator/sangria/contextual/ContextSensitiveBinder.java
import java.lang.annotation.Annotation;
import java.util.*;
import javax.inject.Inject;
import com.google.inject.AbstractModule;
import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.ConfigurationException;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.Dependency;
import com.google.inject.spi.DependencyAndSource;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.spi.ProvisionListener;
import com.tavianator.sangria.core.DelayedError;
import com.tavianator.sangria.core.UniqueAnnotations;
@Override
public ContextSensitiveBindingBuilder<T> annotatedWith(Annotation annotation) {
error.cancel();
return new BindingBuilder<>(Key.get(bindingKey.getTypeLiteral(), annotation));
}
@Override
public void toContextSensitiveProvider(Class<? extends ContextSensitiveProvider<? extends T>> type) {
toContextSensitiveProvider(Key.get(type));
}
@Override
public void toContextSensitiveProvider(TypeLiteral<? extends ContextSensitiveProvider<? extends T>> type) {
toContextSensitiveProvider(Key.get(type));
}
@Override
public void toContextSensitiveProvider(Key<? extends ContextSensitiveProvider<? extends T>> key) {
error.cancel();
Provider<? extends ContextSensitiveProvider<? extends T>> provider = binder.getProvider(makeUniqueLinkedKey(key));
binder.bind(bindingKey).toProvider(new ProviderKeyAdapter<>(provider, key));
binder.bindListener(new BindingMatcher(bindingKey), new Trigger(bindingKey));
}
/**
* For Binder#requireExplicitBindings() support.
*/
private <U> Key<U> makeUniqueLinkedKey(Key<U> key) { | Key<U> linkedKey = Key.get(key.getTypeLiteral(), UniqueAnnotations.create()); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/MobRepulsorModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.Entity;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import java.util.Iterator;
import java.util.List; | package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 8:26 PM 4/25/13
*/
public class MobRepulsorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MOB_REPULSOR = "Mob Repulsor";
public static final String MOB_REPULSOR_ENERGY_CONSUMPTION = "Repulsor Energy Consumption";
public MobRepulsorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MOB_REPULSOR_ENERGY_CONSUMPTION, 250);
addBaseProperty(MuseCommonStrings.WEIGHT, 2000); | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/MobRepulsorModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.Entity;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import java.util.Iterator;
import java.util.List;
package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 8:26 PM 4/25/13
*/
public class MobRepulsorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MOB_REPULSOR = "Mob Repulsor";
public static final String MOB_REPULSOR_ENERGY_CONSUMPTION = "Repulsor Energy Consumption";
public MobRepulsorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MOB_REPULSOR_ENERGY_CONSUMPTION, 250);
addBaseProperty(MuseCommonStrings.WEIGHT, 2000); | addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 1)); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/MobRepulsorModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.Entity;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import java.util.Iterator;
import java.util.List; | package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 8:26 PM 4/25/13
*/
public class MobRepulsorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MOB_REPULSOR = "Mob Repulsor";
public static final String MOB_REPULSOR_ENERGY_CONSUMPTION = "Repulsor Energy Consumption";
public MobRepulsorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MOB_REPULSOR_ENERGY_CONSUMPTION, 250);
addBaseProperty(MuseCommonStrings.WEIGHT, 2000);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
}
@Override
public String getTextureFile() {
return "magneta";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENVIRONMENTAL;
}
@Override
public String getDataName() {
return MODULE_MOB_REPULSOR;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/MobRepulsorModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.Entity;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import java.util.Iterator;
import java.util.List;
package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 8:26 PM 4/25/13
*/
public class MobRepulsorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MOB_REPULSOR = "Mob Repulsor";
public static final String MOB_REPULSOR_ENERGY_CONSUMPTION = "Repulsor Energy Consumption";
public MobRepulsorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MOB_REPULSOR_ENERGY_CONSUMPTION, 250);
addBaseProperty(MuseCommonStrings.WEIGHT, 2000);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
}
@Override
public String getTextureFile() {
return "magneta";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENVIRONMENTAL;
}
@Override
public String getDataName() {
return MODULE_MOB_REPULSOR;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.mobRepulsor.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/InPlaceAssemblerModule.java | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
| import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
public class InPlaceAssemblerModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_PORTABLE_CRAFTING = "In-Place Assembler";
public InPlaceAssemblerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addInstallCost(new ItemStack(Block.workbench, 1));
}
@Override
public String getTextureFile() {
return "portablecrafting";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_PORTABLE_CRAFTING;
}
@Override
public String getLocalizedName() {
return StatCollector.translateToLocal("module.portableCraftingTable.name");
}
@Override
public String getDescription() {
return "A larger crafting grid, on the go.";
}
@Override
public void onRightClick(EntityPlayer player, World world, ItemStack item) { | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/InPlaceAssemblerModule.java
import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
public class InPlaceAssemblerModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_PORTABLE_CRAFTING = "In-Place Assembler";
public InPlaceAssemblerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addInstallCost(new ItemStack(Block.workbench, 1));
}
@Override
public String getTextureFile() {
return "portablecrafting";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_PORTABLE_CRAFTING;
}
@Override
public String getLocalizedName() {
return StatCollector.translateToLocal("module.portableCraftingTable.name");
}
@Override
public String getDescription() {
return "A larger crafting grid, on the go.";
}
@Override
public void onRightClick(EntityPlayer player, World world, ItemStack item) { | player.openGui(ModularPowersuitsAddons.INSTANCE, GuiHandler.craftingGuiID, world, (int) player.posX, (int) player.posY, (int) player.posZ); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/InPlaceAssemblerModule.java | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
| import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
public class InPlaceAssemblerModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_PORTABLE_CRAFTING = "In-Place Assembler";
public InPlaceAssemblerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addInstallCost(new ItemStack(Block.workbench, 1));
}
@Override
public String getTextureFile() {
return "portablecrafting";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_PORTABLE_CRAFTING;
}
@Override
public String getLocalizedName() {
return StatCollector.translateToLocal("module.portableCraftingTable.name");
}
@Override
public String getDescription() {
return "A larger crafting grid, on the go.";
}
@Override
public void onRightClick(EntityPlayer player, World world, ItemStack item) { | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/InPlaceAssemblerModule.java
import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
public class InPlaceAssemblerModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_PORTABLE_CRAFTING = "In-Place Assembler";
public InPlaceAssemblerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addInstallCost(new ItemStack(Block.workbench, 1));
}
@Override
public String getTextureFile() {
return "portablecrafting";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_PORTABLE_CRAFTING;
}
@Override
public String getLocalizedName() {
return StatCollector.translateToLocal("module.portableCraftingTable.name");
}
@Override
public String getDescription() {
return "A larger crafting grid, on the go.";
}
@Override
public void onRightClick(EntityPlayer player, World world, ItemStack item) { | player.openGui(ModularPowersuitsAddons.INSTANCE, GuiHandler.craftingGuiID, world, (int) player.posX, (int) player.posY, (int) player.posZ); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/KineticGeneratorModule.java | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseHeatUtils;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List; | package andrew.powersuits.modules;
public class KineticGeneratorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_KINETIC_GENERATOR = "Kinetic Generator";
public static final String KINETIC_ENERGY_GENERATION = "Energy Per 5 Blocks";
public static final String KINETIC_HEAT_GENERATION = "Heat Generation";
public KineticGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(KINETIC_HEAT_GENERATION, 5);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addBaseProperty(KINETIC_ENERGY_GENERATION, 200);
addTradeoffProperty("Energy Generated", KINETIC_ENERGY_GENERATION, 600, " Joules");
addTradeoffProperty("Energy Generated", MuseCommonStrings.WEIGHT, 3000, "g");
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.servoMotor, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
}
@Override
public String getTextureFile() {
return "kineticgen";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_KINETIC_GENERATOR;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/KineticGeneratorModule.java
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseHeatUtils;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
package andrew.powersuits.modules;
public class KineticGeneratorModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_KINETIC_GENERATOR = "Kinetic Generator";
public static final String KINETIC_ENERGY_GENERATION = "Energy Per 5 Blocks";
public static final String KINETIC_HEAT_GENERATION = "Heat Generation";
public KineticGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(KINETIC_HEAT_GENERATION, 5);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addBaseProperty(KINETIC_ENERGY_GENERATION, 200);
addTradeoffProperty("Energy Generated", KINETIC_ENERGY_GENERATION, 600, " Joules");
addTradeoffProperty("Energy Generated", MuseCommonStrings.WEIGHT, 3000, "g");
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.servoMotor, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
}
@Override
public String getTextureFile() {
return "kineticgen";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_KINETIC_GENERATOR;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.kineticGenerator.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/client/PortableCraftingGui.java | // Path: src/minecraft/andrew/powersuits/container/PortableCraftingContainer.java
// public class PortableCraftingContainer extends ContainerWorkbench {
// public PortableCraftingContainer(InventoryPlayer inventoryPlayer, World world, int x, int y, int z) {
// super(inventoryPlayer, world, x, y, z);
// }
//
// @Override
// public boolean canInteractWith(EntityPlayer player) {
// return true;
// }
//
// @Override
// public void onCraftGuiClosed(EntityPlayer player) {
// super.onCraftGuiClosed(player);
// }
// }
| import andrew.powersuits.container.PortableCraftingContainer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11; | package andrew.powersuits.client;
public class PortableCraftingGui extends GuiContainer {
public PortableCraftingGui(EntityPlayer player, World world, int x, int y, int z) { | // Path: src/minecraft/andrew/powersuits/container/PortableCraftingContainer.java
// public class PortableCraftingContainer extends ContainerWorkbench {
// public PortableCraftingContainer(InventoryPlayer inventoryPlayer, World world, int x, int y, int z) {
// super(inventoryPlayer, world, x, y, z);
// }
//
// @Override
// public boolean canInteractWith(EntityPlayer player) {
// return true;
// }
//
// @Override
// public void onCraftGuiClosed(EntityPlayer player) {
// super.onCraftGuiClosed(player);
// }
// }
// Path: src/minecraft/andrew/powersuits/client/PortableCraftingGui.java
import andrew.powersuits.container.PortableCraftingContainer;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
package andrew.powersuits.client;
public class PortableCraftingGui extends GuiContainer {
public PortableCraftingGui(EntityPlayer player, World world, int x, int y, int z) { | super(new PortableCraftingContainer(player.inventory, world, x, y, z)); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/network/muse/MusePacketOld.java | // Path: src/minecraft/andrew/powersuits/common/AddonLogger.java
// public abstract class AddonLogger {
// public static final Logger logger = Logger.getLogger("MPSA-" + FMLCommonHandler.instance().getEffectiveSide());
// static {
// logger.setParent(FMLLog.getLogger());
// }
//
// public static void logDebug(String string) {
// logger.info(string);
// }
//
// public static void logError(String string) {
// logger.warning(string);
//
// }
// }
//
// Path: src/minecraft/andrew/powersuits/network/AndrewPacketHandler.java
// public class AndrewPacketHandler implements IPacketHandler {
//
// public AndrewPacketHandler register() {
// addPacketType(1, AndrewPacketMagnetMode.class);
//
// NetworkRegistry.instance().registerChannel(this, "psa");
// return this;
// }
//
// public static BiMap<Integer, Constructor<? extends MusePacketOld>> packetConstructors = HashBiMap
// .create();
//
// @Override
// public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player) {
// if (payload.channel.equals(AddonConfig.getNetworkChannelName())) {
// MusePacketOld repackaged = repackage(payload, player);
// if (repackaged != null) {
// Side side = FMLCommonHandler.instance().getEffectiveSide();
// if (side == Side.CLIENT) {
// repackaged.handleClient((EntityClientPlayerMP) player);
// } else if (side == Side.SERVER) {
// repackaged.handleServer((EntityPlayerMP) player);
// }
//
// }
// }
// }
//
// public static MusePacketOld repackage(Packet250CustomPayload payload, Player player) {
// MusePacketOld repackaged = null;
// DataInputStream data = new DataInputStream(new ByteArrayInputStream(payload.data));
// int packetType;
// try {
// packetType = data.readInt();
// repackaged = useConstructor(packetConstructors.get(packetType), data, player);
// } catch (IOException e) {
// AddonLogger.logError("PROBLEM READING PACKET TYPE D:");
// e.printStackTrace();
// return null;
// }
// return repackaged;
// }
//
// /**
// * @param type
// * @return
// */
// public static int getTypeID(MusePacketOld packet) {
// try {
// return packetConstructors.inverse().get(getConstructor(packet.getClass()));
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("PACKET SECURITY PROBLEM D:");
// e.printStackTrace();
// }
// return -150;
// }
//
// /**
// * Returns the constructor of the given object. Keep in sync with
// * useConstructor.
// *
// * @param packetType
// * @return
// * @throws NoSuchMethodException
// * @throws SecurityException
// */
// protected static Constructor<? extends MusePacketOld> getConstructor(Class<? extends MusePacketOld> packetType) throws NoSuchMethodException, SecurityException {
// return packetType.getConstructor(DataInputStream.class, Player.class);
// }
//
// /**
// * Returns a new instance of the object, created via the constructor in
// * question. Keep in sync with getConstructor.
// *
// * @param constructor
// * @return
// */
// protected static MusePacketOld useConstructor(Constructor<? extends MusePacketOld> constructor, DataInputStream data, Player player) {
// try {
// return constructor.newInstance(data, player);
// } catch (InstantiationException e) {
// AddonLogger.logError("PROBLEM INSTATIATING PACKET D:");
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// AddonLogger.logError("PROBLEM ACCESSING PACKET D:");
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// AddonLogger.logError("PROBLEM INVOKING PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean addPacketType(int id, Class<? extends MusePacketOld> packetType) {
// try {
// packetConstructors.put(id, getConstructor(packetType));
// return true;
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": INVALID CONSTRUCTOR");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": SECURITY PROBLEM");
// e.printStackTrace();
// }
// return false;
// }
// }
| import andrew.powersuits.common.AddonLogger;
import andrew.powersuits.network.AndrewPacketHandler;
import cpw.mods.fml.common.network.Player;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException; | package andrew.powersuits.network.muse;
/**
* Created by User: Andrew2448
* 7:40 PM 5/15/13
*/
public abstract class MusePacketOld {
protected static final int READ_ERROR = -150;
protected Player player;
protected ByteArrayOutputStream bytes;
protected Packet250CustomPayload packet;
protected DataOutputStream dataout;
protected DataInputStream datain;
protected int id;
protected MusePacketOld(Player player) {
this.player = player;
this.bytes = new ByteArrayOutputStream();
this.dataout = new DataOutputStream(bytes);
try { | // Path: src/minecraft/andrew/powersuits/common/AddonLogger.java
// public abstract class AddonLogger {
// public static final Logger logger = Logger.getLogger("MPSA-" + FMLCommonHandler.instance().getEffectiveSide());
// static {
// logger.setParent(FMLLog.getLogger());
// }
//
// public static void logDebug(String string) {
// logger.info(string);
// }
//
// public static void logError(String string) {
// logger.warning(string);
//
// }
// }
//
// Path: src/minecraft/andrew/powersuits/network/AndrewPacketHandler.java
// public class AndrewPacketHandler implements IPacketHandler {
//
// public AndrewPacketHandler register() {
// addPacketType(1, AndrewPacketMagnetMode.class);
//
// NetworkRegistry.instance().registerChannel(this, "psa");
// return this;
// }
//
// public static BiMap<Integer, Constructor<? extends MusePacketOld>> packetConstructors = HashBiMap
// .create();
//
// @Override
// public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player) {
// if (payload.channel.equals(AddonConfig.getNetworkChannelName())) {
// MusePacketOld repackaged = repackage(payload, player);
// if (repackaged != null) {
// Side side = FMLCommonHandler.instance().getEffectiveSide();
// if (side == Side.CLIENT) {
// repackaged.handleClient((EntityClientPlayerMP) player);
// } else if (side == Side.SERVER) {
// repackaged.handleServer((EntityPlayerMP) player);
// }
//
// }
// }
// }
//
// public static MusePacketOld repackage(Packet250CustomPayload payload, Player player) {
// MusePacketOld repackaged = null;
// DataInputStream data = new DataInputStream(new ByteArrayInputStream(payload.data));
// int packetType;
// try {
// packetType = data.readInt();
// repackaged = useConstructor(packetConstructors.get(packetType), data, player);
// } catch (IOException e) {
// AddonLogger.logError("PROBLEM READING PACKET TYPE D:");
// e.printStackTrace();
// return null;
// }
// return repackaged;
// }
//
// /**
// * @param type
// * @return
// */
// public static int getTypeID(MusePacketOld packet) {
// try {
// return packetConstructors.inverse().get(getConstructor(packet.getClass()));
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("PACKET SECURITY PROBLEM D:");
// e.printStackTrace();
// }
// return -150;
// }
//
// /**
// * Returns the constructor of the given object. Keep in sync with
// * useConstructor.
// *
// * @param packetType
// * @return
// * @throws NoSuchMethodException
// * @throws SecurityException
// */
// protected static Constructor<? extends MusePacketOld> getConstructor(Class<? extends MusePacketOld> packetType) throws NoSuchMethodException, SecurityException {
// return packetType.getConstructor(DataInputStream.class, Player.class);
// }
//
// /**
// * Returns a new instance of the object, created via the constructor in
// * question. Keep in sync with getConstructor.
// *
// * @param constructor
// * @return
// */
// protected static MusePacketOld useConstructor(Constructor<? extends MusePacketOld> constructor, DataInputStream data, Player player) {
// try {
// return constructor.newInstance(data, player);
// } catch (InstantiationException e) {
// AddonLogger.logError("PROBLEM INSTATIATING PACKET D:");
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// AddonLogger.logError("PROBLEM ACCESSING PACKET D:");
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// AddonLogger.logError("PROBLEM INVOKING PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean addPacketType(int id, Class<? extends MusePacketOld> packetType) {
// try {
// packetConstructors.put(id, getConstructor(packetType));
// return true;
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": INVALID CONSTRUCTOR");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": SECURITY PROBLEM");
// e.printStackTrace();
// }
// return false;
// }
// }
// Path: src/minecraft/andrew/powersuits/network/muse/MusePacketOld.java
import andrew.powersuits.common.AddonLogger;
import andrew.powersuits.network.AndrewPacketHandler;
import cpw.mods.fml.common.network.Player;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
package andrew.powersuits.network.muse;
/**
* Created by User: Andrew2448
* 7:40 PM 5/15/13
*/
public abstract class MusePacketOld {
protected static final int READ_ERROR = -150;
protected Player player;
protected ByteArrayOutputStream bytes;
protected Packet250CustomPayload packet;
protected DataOutputStream dataout;
protected DataInputStream datain;
protected int id;
protected MusePacketOld(Player player) {
this.player = player;
this.bytes = new ByteArrayOutputStream();
this.dataout = new DataOutputStream(bytes);
try { | int id = AndrewPacketHandler.getTypeID(this); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/network/muse/MusePacketOld.java | // Path: src/minecraft/andrew/powersuits/common/AddonLogger.java
// public abstract class AddonLogger {
// public static final Logger logger = Logger.getLogger("MPSA-" + FMLCommonHandler.instance().getEffectiveSide());
// static {
// logger.setParent(FMLLog.getLogger());
// }
//
// public static void logDebug(String string) {
// logger.info(string);
// }
//
// public static void logError(String string) {
// logger.warning(string);
//
// }
// }
//
// Path: src/minecraft/andrew/powersuits/network/AndrewPacketHandler.java
// public class AndrewPacketHandler implements IPacketHandler {
//
// public AndrewPacketHandler register() {
// addPacketType(1, AndrewPacketMagnetMode.class);
//
// NetworkRegistry.instance().registerChannel(this, "psa");
// return this;
// }
//
// public static BiMap<Integer, Constructor<? extends MusePacketOld>> packetConstructors = HashBiMap
// .create();
//
// @Override
// public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player) {
// if (payload.channel.equals(AddonConfig.getNetworkChannelName())) {
// MusePacketOld repackaged = repackage(payload, player);
// if (repackaged != null) {
// Side side = FMLCommonHandler.instance().getEffectiveSide();
// if (side == Side.CLIENT) {
// repackaged.handleClient((EntityClientPlayerMP) player);
// } else if (side == Side.SERVER) {
// repackaged.handleServer((EntityPlayerMP) player);
// }
//
// }
// }
// }
//
// public static MusePacketOld repackage(Packet250CustomPayload payload, Player player) {
// MusePacketOld repackaged = null;
// DataInputStream data = new DataInputStream(new ByteArrayInputStream(payload.data));
// int packetType;
// try {
// packetType = data.readInt();
// repackaged = useConstructor(packetConstructors.get(packetType), data, player);
// } catch (IOException e) {
// AddonLogger.logError("PROBLEM READING PACKET TYPE D:");
// e.printStackTrace();
// return null;
// }
// return repackaged;
// }
//
// /**
// * @param type
// * @return
// */
// public static int getTypeID(MusePacketOld packet) {
// try {
// return packetConstructors.inverse().get(getConstructor(packet.getClass()));
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("PACKET SECURITY PROBLEM D:");
// e.printStackTrace();
// }
// return -150;
// }
//
// /**
// * Returns the constructor of the given object. Keep in sync with
// * useConstructor.
// *
// * @param packetType
// * @return
// * @throws NoSuchMethodException
// * @throws SecurityException
// */
// protected static Constructor<? extends MusePacketOld> getConstructor(Class<? extends MusePacketOld> packetType) throws NoSuchMethodException, SecurityException {
// return packetType.getConstructor(DataInputStream.class, Player.class);
// }
//
// /**
// * Returns a new instance of the object, created via the constructor in
// * question. Keep in sync with getConstructor.
// *
// * @param constructor
// * @return
// */
// protected static MusePacketOld useConstructor(Constructor<? extends MusePacketOld> constructor, DataInputStream data, Player player) {
// try {
// return constructor.newInstance(data, player);
// } catch (InstantiationException e) {
// AddonLogger.logError("PROBLEM INSTATIATING PACKET D:");
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// AddonLogger.logError("PROBLEM ACCESSING PACKET D:");
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// AddonLogger.logError("PROBLEM INVOKING PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean addPacketType(int id, Class<? extends MusePacketOld> packetType) {
// try {
// packetConstructors.put(id, getConstructor(packetType));
// return true;
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": INVALID CONSTRUCTOR");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": SECURITY PROBLEM");
// e.printStackTrace();
// }
// return false;
// }
// }
| import andrew.powersuits.common.AddonLogger;
import andrew.powersuits.network.AndrewPacketHandler;
import cpw.mods.fml.common.network.Player;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException; |
protected MusePacketOld(DataInputStream data, Player player) {
this.player = player;
this.datain = data;
}
/**
* Gets the MC packet associated with this MusePacket
*
* @return Packet250CustomPayload
*/
public Packet250CustomPayload getPacket250() {
return new Packet250CustomPayload(Config.getNetworkChannelName(),
bytes.toByteArray());
}
/**
* Called by the network manager since it does all the packet mapping
*
* @param player
*/
public abstract void handleClient(EntityClientPlayerMP player);
public abstract void handleServer(EntityPlayerMP player);
public int readInt() {
try {
int read = datain.readInt();
return read;
} catch (IOException e) { | // Path: src/minecraft/andrew/powersuits/common/AddonLogger.java
// public abstract class AddonLogger {
// public static final Logger logger = Logger.getLogger("MPSA-" + FMLCommonHandler.instance().getEffectiveSide());
// static {
// logger.setParent(FMLLog.getLogger());
// }
//
// public static void logDebug(String string) {
// logger.info(string);
// }
//
// public static void logError(String string) {
// logger.warning(string);
//
// }
// }
//
// Path: src/minecraft/andrew/powersuits/network/AndrewPacketHandler.java
// public class AndrewPacketHandler implements IPacketHandler {
//
// public AndrewPacketHandler register() {
// addPacketType(1, AndrewPacketMagnetMode.class);
//
// NetworkRegistry.instance().registerChannel(this, "psa");
// return this;
// }
//
// public static BiMap<Integer, Constructor<? extends MusePacketOld>> packetConstructors = HashBiMap
// .create();
//
// @Override
// public void onPacketData(INetworkManager manager, Packet250CustomPayload payload, Player player) {
// if (payload.channel.equals(AddonConfig.getNetworkChannelName())) {
// MusePacketOld repackaged = repackage(payload, player);
// if (repackaged != null) {
// Side side = FMLCommonHandler.instance().getEffectiveSide();
// if (side == Side.CLIENT) {
// repackaged.handleClient((EntityClientPlayerMP) player);
// } else if (side == Side.SERVER) {
// repackaged.handleServer((EntityPlayerMP) player);
// }
//
// }
// }
// }
//
// public static MusePacketOld repackage(Packet250CustomPayload payload, Player player) {
// MusePacketOld repackaged = null;
// DataInputStream data = new DataInputStream(new ByteArrayInputStream(payload.data));
// int packetType;
// try {
// packetType = data.readInt();
// repackaged = useConstructor(packetConstructors.get(packetType), data, player);
// } catch (IOException e) {
// AddonLogger.logError("PROBLEM READING PACKET TYPE D:");
// e.printStackTrace();
// return null;
// }
// return repackaged;
// }
//
// /**
// * @param type
// * @return
// */
// public static int getTypeID(MusePacketOld packet) {
// try {
// return packetConstructors.inverse().get(getConstructor(packet.getClass()));
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("PACKET SECURITY PROBLEM D:");
// e.printStackTrace();
// }
// return -150;
// }
//
// /**
// * Returns the constructor of the given object. Keep in sync with
// * useConstructor.
// *
// * @param packetType
// * @return
// * @throws NoSuchMethodException
// * @throws SecurityException
// */
// protected static Constructor<? extends MusePacketOld> getConstructor(Class<? extends MusePacketOld> packetType) throws NoSuchMethodException, SecurityException {
// return packetType.getConstructor(DataInputStream.class, Player.class);
// }
//
// /**
// * Returns a new instance of the object, created via the constructor in
// * question. Keep in sync with getConstructor.
// *
// * @param constructor
// * @return
// */
// protected static MusePacketOld useConstructor(Constructor<? extends MusePacketOld> constructor, DataInputStream data, Player player) {
// try {
// return constructor.newInstance(data, player);
// } catch (InstantiationException e) {
// AddonLogger.logError("PROBLEM INSTATIATING PACKET D:");
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// AddonLogger.logError("PROBLEM ACCESSING PACKET D:");
// e.printStackTrace();
// } catch (IllegalArgumentException e) {
// AddonLogger.logError("INVALID PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// } catch (InvocationTargetException e) {
// AddonLogger.logError("PROBLEM INVOKING PACKET CONSTRUCTOR D:");
// e.printStackTrace();
// }
// return null;
// }
//
// public static boolean addPacketType(int id, Class<? extends MusePacketOld> packetType) {
// try {
// packetConstructors.put(id, getConstructor(packetType));
// return true;
// } catch (NoSuchMethodException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": INVALID CONSTRUCTOR");
// e.printStackTrace();
// } catch (SecurityException e) {
// AddonLogger.logError("UNABLE TO REGISTER PACKET TYPE: "
// + packetType + ": SECURITY PROBLEM");
// e.printStackTrace();
// }
// return false;
// }
// }
// Path: src/minecraft/andrew/powersuits/network/muse/MusePacketOld.java
import andrew.powersuits.common.AddonLogger;
import andrew.powersuits.network.AndrewPacketHandler;
import cpw.mods.fml.common.network.Player;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
protected MusePacketOld(DataInputStream data, Player player) {
this.player = player;
this.datain = data;
}
/**
* Gets the MC packet associated with this MusePacket
*
* @return Packet250CustomPayload
*/
public Packet250CustomPayload getPacket250() {
return new Packet250CustomPayload(Config.getNetworkChannelName(),
bytes.toByteArray());
}
/**
* Called by the network manager since it does all the packet mapping
*
* @param player
*/
public abstract void handleClient(EntityClientPlayerMP player);
public abstract void handleServer(EntityPlayerMP player);
public int readInt() {
try {
int read = datain.readInt();
return read;
} catch (IOException e) { | AddonLogger.logError("PROBLEM READING INT FROM PACKET D:"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/LightningModule.java | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.*;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 5:56 PM 6/14/13
*/
public class LightningModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_LIGHTNING = "Lightning Summoner";
public static final String LIGHTNING_ENERGY_CONSUMPTION = "Lightning Energy Consumption";
public static final String HEAT = "Lightning Heat Emission";
public LightningModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.hvcapacitor, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.fieldEmitter, 2));
addBaseProperty(LIGHTNING_ENERGY_CONSUMPTION, 500000, "");
addBaseProperty(HEAT, 100, "");
}
@Override
public String getTextureFile() {
return "bluestar";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_WEAPON;
}
@Override
public String getDataName() {
return MODULE_LIGHTNING;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/LightningModule.java
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.*;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 5:56 PM 6/14/13
*/
public class LightningModule extends PowerModuleBase implements IRightClickModule {
public static final String MODULE_LIGHTNING = "Lightning Summoner";
public static final String LIGHTNING_ENERGY_CONSUMPTION = "Lightning Energy Consumption";
public static final String HEAT = "Lightning Heat Emission";
public LightningModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.hvcapacitor, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.fieldEmitter, 2));
addBaseProperty(LIGHTNING_ENERGY_CONSUMPTION, 500000, "");
addBaseProperty(HEAT, 100, "");
}
@Override
public String getTextureFile() {
return "bluestar";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_WEAPON;
}
@Override
public String getDataName() {
return MODULE_LIGHTNING;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.lightningSummoner.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/ThermalGeneratorModule.java | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.common.ModCompatability;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseHeatUtils;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List; | addBaseProperty(THERMAL_ENERGY_GENERATION, 25);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addTradeoffProperty("Energy Generated", THERMAL_ENERGY_GENERATION, 25, " Joules");
addTradeoffProperty("Energy Generated", MuseCommonStrings.WEIGHT, 1000, "g");
if (ModCompatability.isIndustrialCraftLoaded()) {
addInstallCost(ModCompatability.getIC2Item("geothermalGenerator"));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
} else {
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.basicPlating, 1));
}
}
@Override
public String getTextureFile() {
return "heatgenerator";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_THERMAL_GENERATOR;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/ThermalGeneratorModule.java
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.common.ModCompatability;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseHeatUtils;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List;
addBaseProperty(THERMAL_ENERGY_GENERATION, 25);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addTradeoffProperty("Energy Generated", THERMAL_ENERGY_GENERATION, 25, " Joules");
addTradeoffProperty("Energy Generated", MuseCommonStrings.WEIGHT, 1000, "g");
if (ModCompatability.isIndustrialCraftLoaded()) {
addInstallCost(ModCompatability.getIC2Item("geothermalGenerator"));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
} else {
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.basicPlating, 1));
}
}
@Override
public String getTextureFile() {
return "heatgenerator";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_THERMAL_GENERATOR;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.thermalGenerator.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/book/page/ContentsPage.java | // Path: src/minecraft/andrew/powersuits/book/BookRegistry.java
// public class BookRegistry {
//
// public static Map<String, ItemStack> manualIcons = new HashMap<String, ItemStack>();
// public static ItemStack defaultStack = new ItemStack(Item.ingotIron);
//
// public static void registerManualIcon (String name, ItemStack stack) {
// manualIcons.put(name, stack);
// }
//
// public static ItemStack getManualIcon (String textContent) {
// ItemStack stack = manualIcons.get(textContent);
// if (stack != null)
// return stack;
// return defaultStack;
// }
// }
| import andrew.powersuits.book.BookRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList; | package andrew.powersuits.book.page;
/**
* Created by User: Andrew2448
* 2:17 PM 7/27/13
*/
public class ContentsPage extends BookPage {
String text;
String[] iconText;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("link");
iconText = new String[nodes.getLength()];
icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
iconText[i] = children.item(1).getTextContent(); | // Path: src/minecraft/andrew/powersuits/book/BookRegistry.java
// public class BookRegistry {
//
// public static Map<String, ItemStack> manualIcons = new HashMap<String, ItemStack>();
// public static ItemStack defaultStack = new ItemStack(Item.ingotIron);
//
// public static void registerManualIcon (String name, ItemStack stack) {
// manualIcons.put(name, stack);
// }
//
// public static ItemStack getManualIcon (String textContent) {
// ItemStack stack = manualIcons.get(textContent);
// if (stack != null)
// return stack;
// return defaultStack;
// }
// }
// Path: src/minecraft/andrew/powersuits/book/page/ContentsPage.java
import andrew.powersuits.book.BookRegistry;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
package andrew.powersuits.book.page;
/**
* Created by User: Andrew2448
* 2:17 PM 7/27/13
*/
public class ContentsPage extends BookPage {
String text;
String[] iconText;
ItemStack[] icons;
@Override
public void readPageFromXML (Element element)
{
NodeList nodes = element.getElementsByTagName("text");
if (nodes != null)
text = nodes.item(0).getTextContent();
nodes = element.getElementsByTagName("link");
iconText = new String[nodes.getLength()];
icons = new ItemStack[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++)
{
NodeList children = nodes.item(i).getChildNodes();
iconText[i] = children.item(1).getTextContent(); | icons[i] = BookRegistry.getManualIcon(children.item(3).getTextContent()); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/SolarGeneratorModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
public class SolarGeneratorModule extends PowerModuleBase implements IPlayerTickModule {
public static final String MODULE_SOLAR_GENERATOR = "Solar Generator";
public static final String SOLAR_ENERGY_GENERATION_DAY = "Daytime Energy Generation";
public static final String SOLAR_ENERGY_GENERATION_NIGHT = "Nighttime Energy Generation";
public SolarGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(SOLAR_ENERGY_GENERATION_DAY, 1500);
addBaseProperty(SOLAR_ENERGY_GENERATION_NIGHT, 150); | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/SolarGeneratorModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
public class SolarGeneratorModule extends PowerModuleBase implements IPlayerTickModule {
public static final String MODULE_SOLAR_GENERATOR = "Solar Generator";
public static final String SOLAR_ENERGY_GENERATION_DAY = "Daytime Energy Generation";
public static final String SOLAR_ENERGY_GENERATION_NIGHT = "Nighttime Energy Generation";
public SolarGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(SOLAR_ENERGY_GENERATION_DAY, 1500);
addBaseProperty(SOLAR_ENERGY_GENERATION_NIGHT, 150); | addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.solarPanel, 1)); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/SolarGeneratorModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
public class SolarGeneratorModule extends PowerModuleBase implements IPlayerTickModule {
public static final String MODULE_SOLAR_GENERATOR = "Solar Generator";
public static final String SOLAR_ENERGY_GENERATION_DAY = "Daytime Energy Generation";
public static final String SOLAR_ENERGY_GENERATION_NIGHT = "Nighttime Energy Generation";
public SolarGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(SOLAR_ENERGY_GENERATION_DAY, 1500);
addBaseProperty(SOLAR_ENERGY_GENERATION_NIGHT, 150);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.solarPanel, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
}
@Override
public String getTextureFile() {
return "solarhelmet";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_SOLAR_GENERATOR;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/SolarGeneratorModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
public class SolarGeneratorModule extends PowerModuleBase implements IPlayerTickModule {
public static final String MODULE_SOLAR_GENERATOR = "Solar Generator";
public static final String SOLAR_ENERGY_GENERATION_DAY = "Daytime Energy Generation";
public static final String SOLAR_ENERGY_GENERATION_NIGHT = "Nighttime Energy Generation";
public SolarGeneratorModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(SOLAR_ENERGY_GENERATION_DAY, 1500);
addBaseProperty(SOLAR_ENERGY_GENERATION_NIGHT, 150);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.solarPanel, 1));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
}
@Override
public String getTextureFile() {
return "solarhelmet";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_SOLAR_GENERATOR;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.solarGenerator.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/book/ItemBook.java | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
| import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World; | package andrew.powersuits.book;
/**
* Created by User: Andrew2448
* 11:54 PM 7/26/13
*/
public class ItemBook extends Item {
public ItemBook(int i) {
super(i);
setMaxStackSize(1);
setCreativeTab(Config.getCreativeTab());
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
// Path: src/minecraft/andrew/powersuits/book/ItemBook.java
import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
package andrew.powersuits.book;
/**
* Created by User: Andrew2448
* 11:54 PM 7/26/13
*/
public class ItemBook extends Item {
public ItemBook(int i) {
super(i);
setMaxStackSize(1);
setCreativeTab(Config.getCreativeTab());
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { | player.openGui(ModularPowersuitsAddons.INSTANCE, GuiHandler.manualGuiID, world, 0, 0, 0); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/book/ItemBook.java | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
| import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World; | package andrew.powersuits.book;
/**
* Created by User: Andrew2448
* 11:54 PM 7/26/13
*/
public class ItemBook extends Item {
public ItemBook(int i) {
super(i);
setMaxStackSize(1);
setCreativeTab(Config.getCreativeTab());
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { | // Path: src/minecraft/andrew/powersuits/common/GuiHandler.java
// public class GuiHandler implements IGuiHandler {
//
// public static int craftingGuiID = 0;
// public static int manualGuiID = 1;
//
// @Override
// public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingContainer(player.inventory, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// default:
// return null;
// }
// }
//
// @Override
// public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
// switch (ID) {
// case 0:
// return new PortableCraftingGui(player, world, (int) player.posX, (int) player.posY, (int) player.posZ);
// case 1:
// ItemStack stack = player.getCurrentEquippedItem();
// return new ManualGui(stack, ClientProxy.manual);
// default:
// return null;
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/ModularPowersuitsAddons.java
// @Mod(modid = "PowersuitAddons", name = "Andrew's Modular Powersuits Addons", version = "@VERSION@", dependencies = "required-after:mmmPowersuits", acceptedMinecraftVersions = "[1.5,)")
// @NetworkMod(clientSideRequired = true, serverSideRequired = false,
// clientPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class),
// serverPacketHandlerSpec = @SidedPacketHandler(channels = {"psa"}, packetHandler = AndrewPacketHandler.class))
// public class ModularPowersuitsAddons {
//
// public static GuiHandler guiHandler = new GuiHandler();
//
// public static ItemBook book;
//
// @Instance("PowersuitAddons")
// public static ModularPowersuitsAddons INSTANCE;
//
// @SidedProxy(clientSide = "andrew.powersuits.client.ClientProxy", serverSide = "andrew.powersuits.common.CommonProxy")
// public static CommonProxy proxy;
//
// @PreInit
// public void preInit(FMLPreInitializationEvent event) {
// AddonConfig.setConfigFolderBase(event.getModConfigurationDirectory());
// AddonConfig.initItems();
// proxy.registerRenderers();
// //proxy.readManuals();
// }
//
// @Init
// public void load(FMLInitializationEvent event) {
// //book = new ItemBook(AddonConfig.manualID);
// AddonComponent.populate();
// AddonConfig.loadPowerModules();
// Localization.loadCurrentLanguage();
// AddonConfig.loadOptions();
// proxy.registerHandlers();
// NetworkRegistry.instance().registerGuiHandler(this, guiHandler);
// }
//
// @PostInit
// public void postInit(FMLPostInitializationEvent event) {
// AddonRecipeManager.addRecipes();
// AddonConfig.getConfig().save();
// }
// }
// Path: src/minecraft/andrew/powersuits/book/ItemBook.java
import andrew.powersuits.common.GuiHandler;
import andrew.powersuits.common.ModularPowersuitsAddons;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.machinemuse.powersuits.common.Config;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
package andrew.powersuits.book;
/**
* Created by User: Andrew2448
* 11:54 PM 7/26/13
*/
public class ItemBook extends Item {
public ItemBook(int i) {
super(i);
setMaxStackSize(1);
setCreativeTab(Config.getCreativeTab());
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { | player.openGui(ModularPowersuitsAddons.INSTANCE, GuiHandler.manualGuiID, world, 0, 0, 0); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/common/AddonWaterUtils.java | // Path: src/minecraft/andrew/powersuits/modules/WaterTankModule.java
// public class WaterTankModule extends PowerModuleBase implements IPlayerTickModule {
// public static final String MODULE_WATER_TANK = "Water Tank";
// public static final String WATER_TANK_SIZE = "Tank Size";
// public static final String ACTIVATION_PERCENT = "Heat Activation Percent";
// ItemStack bucketWater = new ItemStack(Item.bucketWater);
//
// public WaterTankModule(List<IModularItem> validItems) {
// super(validItems);
// addBaseProperty(WATER_TANK_SIZE, 200);
// addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
// addBaseProperty(ACTIVATION_PERCENT, 0.5);
// addTradeoffProperty("Activation Percent", ACTIVATION_PERCENT, 0.5, "%");
// addTradeoffProperty("Tank Size", WATER_TANK_SIZE, 800, " buckets");
// addTradeoffProperty("Tank Size", MuseCommonStrings.WEIGHT, 4000, "g");
// addInstallCost(new ItemStack(Item.bucketWater));
// addInstallCost(new ItemStack(Block.glass, 8));
// addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
// }
//
// @Override
// public String getTextureFile() {
// return null;
// }
//
// @Override
// public Icon getIcon(ItemStack item) {
// return bucketWater.getIconIndex();
// }
//
// @Override
// public String getCategory() {
// return MuseCommonStrings.CATEGORY_ENVIRONMENTAL;
// }
//
// @Override
// public String getDataName() {
// return MODULE_WATER_TANK;
// }
//
// @Override
// public String getLocalizedName() {
// return Localization.translate("module.waterTank.name");
// }
//
// @Override
// public String getDescription() {
// return "Store water which can later be used to cool yourself in emergency situations.";
// }
//
// @Override
// public void onPlayerTickActive(EntityPlayer player, ItemStack item) {
// if (AddonUtils.getWaterLevel(item) > ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, ModuleManager.computeModularProperty(item, WATER_TANK_SIZE));
// }
// if (player.isInWater() && AddonUtils.getWaterLevel(item) < ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) + 1);
// }
// int xCoord = MathHelper.floor_double(player.posX);
// int zCoord = MathHelper.floor_double(player.posZ);
// boolean isRaining = (player.worldObj.getWorldChunkManager().getBiomeGenAt(xCoord, zCoord).getIntRainfall() > 0) && (player.worldObj.isRaining() || player.worldObj.isThundering());
// if (isRaining && player.worldObj.canBlockSeeTheSky(xCoord, MathHelper.floor_double(player.posY) + 1, zCoord) && (player.worldObj.getTotalWorldTime() % 5) == 0 && AddonUtils.getWaterLevel(item) < ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) + 1);
// }
// double currentHeat = MuseHeatUtils.getPlayerHeat(player);
// double maxHeat = MuseHeatUtils.getMaxHeat(player);
// if ((currentHeat / maxHeat) >= ModuleManager.computeModularProperty(item, ACTIVATION_PERCENT) && AddonUtils.getWaterLevel(item) > 0) {
// MuseHeatUtils.coolPlayer(player, 1);
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) - 1);
// for (int i = 0; i < 4; i++) {
// player.worldObj.spawnParticle("smoke", player.posX, player.posY + 0.5, player.posZ, 0.0D, 0.0D, 0.0D);
// }
// }
// }
//
// @Override
// public void onPlayerTickInactive(EntityPlayer player, ItemStack item) {
// }
// }
| import andrew.powersuits.modules.WaterTankModule;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.powersuits.item.ItemPowerArmorChestplate;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; | package andrew.powersuits.common;
/**
* Created by User: Andrew2448
* 4:52 PM 6/21/13
*/
public class AddonWaterUtils {
public static double getPlayerWater(EntityPlayer player) {
double water = 0;
for (ItemStack stack : MuseItemUtils.getModularItemsInInventory(player)) { | // Path: src/minecraft/andrew/powersuits/modules/WaterTankModule.java
// public class WaterTankModule extends PowerModuleBase implements IPlayerTickModule {
// public static final String MODULE_WATER_TANK = "Water Tank";
// public static final String WATER_TANK_SIZE = "Tank Size";
// public static final String ACTIVATION_PERCENT = "Heat Activation Percent";
// ItemStack bucketWater = new ItemStack(Item.bucketWater);
//
// public WaterTankModule(List<IModularItem> validItems) {
// super(validItems);
// addBaseProperty(WATER_TANK_SIZE, 200);
// addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
// addBaseProperty(ACTIVATION_PERCENT, 0.5);
// addTradeoffProperty("Activation Percent", ACTIVATION_PERCENT, 0.5, "%");
// addTradeoffProperty("Tank Size", WATER_TANK_SIZE, 800, " buckets");
// addTradeoffProperty("Tank Size", MuseCommonStrings.WEIGHT, 4000, "g");
// addInstallCost(new ItemStack(Item.bucketWater));
// addInstallCost(new ItemStack(Block.glass, 8));
// addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 2));
// }
//
// @Override
// public String getTextureFile() {
// return null;
// }
//
// @Override
// public Icon getIcon(ItemStack item) {
// return bucketWater.getIconIndex();
// }
//
// @Override
// public String getCategory() {
// return MuseCommonStrings.CATEGORY_ENVIRONMENTAL;
// }
//
// @Override
// public String getDataName() {
// return MODULE_WATER_TANK;
// }
//
// @Override
// public String getLocalizedName() {
// return Localization.translate("module.waterTank.name");
// }
//
// @Override
// public String getDescription() {
// return "Store water which can later be used to cool yourself in emergency situations.";
// }
//
// @Override
// public void onPlayerTickActive(EntityPlayer player, ItemStack item) {
// if (AddonUtils.getWaterLevel(item) > ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, ModuleManager.computeModularProperty(item, WATER_TANK_SIZE));
// }
// if (player.isInWater() && AddonUtils.getWaterLevel(item) < ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) + 1);
// }
// int xCoord = MathHelper.floor_double(player.posX);
// int zCoord = MathHelper.floor_double(player.posZ);
// boolean isRaining = (player.worldObj.getWorldChunkManager().getBiomeGenAt(xCoord, zCoord).getIntRainfall() > 0) && (player.worldObj.isRaining() || player.worldObj.isThundering());
// if (isRaining && player.worldObj.canBlockSeeTheSky(xCoord, MathHelper.floor_double(player.posY) + 1, zCoord) && (player.worldObj.getTotalWorldTime() % 5) == 0 && AddonUtils.getWaterLevel(item) < ModuleManager.computeModularProperty(item, WATER_TANK_SIZE)) {
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) + 1);
// }
// double currentHeat = MuseHeatUtils.getPlayerHeat(player);
// double maxHeat = MuseHeatUtils.getMaxHeat(player);
// if ((currentHeat / maxHeat) >= ModuleManager.computeModularProperty(item, ACTIVATION_PERCENT) && AddonUtils.getWaterLevel(item) > 0) {
// MuseHeatUtils.coolPlayer(player, 1);
// AddonUtils.setWaterLevel(item, AddonUtils.getWaterLevel(item) - 1);
// for (int i = 0; i < 4; i++) {
// player.worldObj.spawnParticle("smoke", player.posX, player.posY + 0.5, player.posZ, 0.0D, 0.0D, 0.0D);
// }
// }
// }
//
// @Override
// public void onPlayerTickInactive(EntityPlayer player, ItemStack item) {
// }
// }
// Path: src/minecraft/andrew/powersuits/common/AddonWaterUtils.java
import andrew.powersuits.modules.WaterTankModule;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.powersuits.item.ItemPowerArmorChestplate;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
package andrew.powersuits.common;
/**
* Created by User: Andrew2448
* 4:52 PM 6/21/13
*/
public class AddonWaterUtils {
public static double getPlayerWater(EntityPlayer player) {
double water = 0;
for (ItemStack stack : MuseItemUtils.getModularItemsInInventory(player)) { | if (stack.getItem() instanceof ItemPowerArmorChestplate && MuseItemUtils.itemHasActiveModule(stack, WaterTankModule.MODULE_WATER_TANK)) { |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlower;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.List; | package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 7:13 PM 4/21/13
*/
public class LeafBlowerModule extends PowerModuleBase implements IRightClickModule {
private static final String MODULE_LEAF_BLOWER = "Leaf Blower";
private static final String LEAF_BLOWER_ENERGY_CONSUMPTION = "Energy Consumption";
private static final String PLANT_RADIUS = "Plant Radius";
private static final String LEAF_RADIUS = "Leaf Radius";
public LeafBlowerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(new ItemStack(Item.ingotIron, 3));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 1));
addBaseProperty(LEAF_BLOWER_ENERGY_CONSUMPTION, 100, "J");
addBaseProperty(PLANT_RADIUS, 1, "m");
addBaseProperty(LEAF_RADIUS, 1, "m");
addIntTradeoffProperty(PLANT_RADIUS, PLANT_RADIUS, 2, "m", 1, 0);
addIntTradeoffProperty(LEAF_RADIUS, LEAF_RADIUS, 2, "m", 1, 0);
}
public PowerModuleBase addIntTradeoffProperty(String tradeoffName, String propertyName, double multiplier, String unit, int roundTo, int offset) {
units.put(propertyName, unit);
return addPropertyModifier(propertyName, new PropertyModifierIntLinearAdditive(tradeoffName, multiplier, roundTo, offset));
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_TOOL;
}
@Override
public String getDataName() {
return MODULE_LEAF_BLOWER;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/LeafBlowerModule.java
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IRightClickModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFlower;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.List;
package andrew.powersuits.modules;
/**
* Created by User: Andrew2448
* 7:13 PM 4/21/13
*/
public class LeafBlowerModule extends PowerModuleBase implements IRightClickModule {
private static final String MODULE_LEAF_BLOWER = "Leaf Blower";
private static final String LEAF_BLOWER_ENERGY_CONSUMPTION = "Energy Consumption";
private static final String PLANT_RADIUS = "Plant Radius";
private static final String LEAF_RADIUS = "Leaf Radius";
public LeafBlowerModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(new ItemStack(Item.ingotIron, 3));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.solenoid, 1));
addBaseProperty(LEAF_BLOWER_ENERGY_CONSUMPTION, 100, "J");
addBaseProperty(PLANT_RADIUS, 1, "m");
addBaseProperty(LEAF_RADIUS, 1, "m");
addIntTradeoffProperty(PLANT_RADIUS, PLANT_RADIUS, 2, "m", 1, 0);
addIntTradeoffProperty(LEAF_RADIUS, LEAF_RADIUS, 2, "m", 1, 0);
}
public PowerModuleBase addIntTradeoffProperty(String tradeoffName, String propertyName, double multiplier, String unit, int roundTo, int offset) {
units.put(propertyName, unit);
return addPropertyModifier(propertyName, new PropertyModifierIntLinearAdditive(tradeoffName, multiplier, roundTo, offset));
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_TOOL;
}
@Override
public String getDataName() {
return MODULE_LEAF_BLOWER;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.leafBlower.name"); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/MagnetModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List; | package andrew.powersuits.modules;
public class MagnetModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MAGNET = "Magnet";
public static final String MAGNET_ENERGY_CONSUMPTION = "Energy Consumption";
public MagnetModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000); | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/MagnetModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List;
package andrew.powersuits.modules;
public class MagnetModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MAGNET = "Magnet";
public static final String MAGNET_ENERGY_CONSUMPTION = "Energy Consumption";
public MagnetModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000); | addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 2)); |
Andrew2448/Andrew2448PowersuitAddons | src/minecraft/andrew/powersuits/modules/MagnetModule.java | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
| import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List; | package andrew.powersuits.modules;
public class MagnetModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MAGNET = "Magnet";
public static final String MAGNET_ENERGY_CONSUMPTION = "Energy Consumption";
public MagnetModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addBaseProperty(MAGNET_ENERGY_CONSUMPTION, 200);
}
@Override
public String getTextureFile() {
return "magnetmodule";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_MAGNET;
}
@Override
public String getLocalizedName() { | // Path: src/minecraft/andrew/powersuits/common/AddonComponent.java
// public class AddonComponent {
// public static ItemStack magnet;
// public static ItemStack solarPanel;
// public static ItemStack computerChip;
//
// public static void populate() {
// if (ModularPowersuits.components != null) {
// solarPanel = ModularPowersuits.components.addComponent("componentSolarPanel", "A light sensitive device that will generate electricity from the sun.", "solarpanel");
// magnet = ModularPowersuits.components.addComponent("componentMagnet", "A metallic device that generates a magnetic field which pulls items towards the player.", "magnetb");
// computerChip = ModularPowersuits.components.addComponent("componentComputerChip", "An upgraded control circuit that contains a CPU which is capable of more advanced calculations.", "computerchip");
// }
// else {
// AddonLogger.logError("MPS components were not initialized, MPSA componenets will not be activated.");
// }
// }
//
// }
//
// Path: src/minecraft/andrew/powersuits/common/Localization.java
// public class Localization {
// public static final String LANG_PATH = "/mods/PowersuitAddons/lang/";
// public static String extractedLanguage = "";
//
// public static String getCurrentLanguage() {
// return StringTranslate.getInstance().getCurrentLanguage();
// }
//
// public static void loadCurrentLanguage() {
// if (getCurrentLanguage() != extractedLanguage) {
// extractedLanguage = getCurrentLanguage();
// }
// try {
// InputStream inputStream = ModularPowersuitsAddons.INSTANCE.getClass().getResourceAsStream(LANG_PATH + extractedLanguage + ".lang");
// Properties langPack = new Properties();
// langPack.load(new InputStreamReader(inputStream, Charsets.UTF_8));
// LanguageRegistry.instance().addStringLocalization(langPack, extractedLanguage);
// } catch (Exception e) {
// e.printStackTrace();
// AddonLogger.logError("Couldn't read MPSA localizations for language " + extractedLanguage + " :(");
// }
// }
//
// public static String translate(String str) {
// loadCurrentLanguage();
// return StatCollector.translateToLocal(str);
// }
// }
// Path: src/minecraft/andrew/powersuits/modules/MagnetModule.java
import andrew.powersuits.common.AddonComponent;
import andrew.powersuits.common.Localization;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.api.moduletrigger.IPlayerTickModule;
import net.machinemuse.api.moduletrigger.IToggleableModule;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import java.util.List;
package andrew.powersuits.modules;
public class MagnetModule extends PowerModuleBase implements IPlayerTickModule, IToggleableModule {
public static final String MODULE_MAGNET = "Magnet";
public static final String MAGNET_ENERGY_CONSUMPTION = "Energy Consumption";
public MagnetModule(List<IModularItem> validItems) {
super(validItems);
addBaseProperty(MuseCommonStrings.WEIGHT, 1000);
addInstallCost(MuseItemUtils.copyAndResize(AddonComponent.magnet, 2));
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1));
addBaseProperty(MAGNET_ENERGY_CONSUMPTION, 200);
}
@Override
public String getTextureFile() {
return "magnetmodule";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_SPECIAL;
}
@Override
public String getDataName() {
return MODULE_MAGNET;
}
@Override
public String getLocalizedName() { | return Localization.translate("module.magnet.name"); |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_ForceWindowsTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.nativehelper.Platforms;
import io.github.mike10004.subprocess.SubprocessLaunchException;
import com.github.mike10004.xvfbmanager.XvfbController;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*; | public void testDisablingOnWindows() throws Exception {
System.out.format("testCase = %s%n", testCase);
AtomicBoolean reachedPreBefore = new AtomicBoolean(false);
RuleUser ruleUser = new RuleUser(testCase.rule) {
@Override
protected void getControllerAndUse(XvfbRule rule) throws Exception {
if (testCase.invokeGetController) {
super.getControllerAndUse(rule);
}
}
@Override
protected void preBefore() throws Exception {
reachedPreBefore.set(true);
}
@Override
protected void postBefore() throws Exception {
assertFalse("made it past before() with eager start", testCase.eagerStart);
}
@Override
protected void preAfter() throws Exception {
}
@Override
protected void postAfter() throws Exception {
}
@Override | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_ForceWindowsTest.java
import com.github.mike10004.nativehelper.Platforms;
import io.github.mike10004.subprocess.SubprocessLaunchException;
import com.github.mike10004.xvfbmanager.XvfbController;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public void testDisablingOnWindows() throws Exception {
System.out.format("testCase = %s%n", testCase);
AtomicBoolean reachedPreBefore = new AtomicBoolean(false);
RuleUser ruleUser = new RuleUser(testCase.rule) {
@Override
protected void getControllerAndUse(XvfbRule rule) throws Exception {
if (testCase.invokeGetController) {
super.getControllerAndUse(rule);
}
}
@Override
protected void preBefore() throws Exception {
reachedPreBefore.set(true);
}
@Override
protected void postBefore() throws Exception {
assertFalse("made it past before() with eager start", testCase.eagerStart);
}
@Override
protected void preAfter() throws Exception {
}
@Override
protected void postAfter() throws Exception {
}
@Override | protected void use(XvfbController ctrl) throws Exception { |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/RuleUser.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.xvfbmanager.XvfbController;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; | package com.github.mike10004.xvfbtesting;
abstract class RuleUser {
private final XvfbRule xvfb;
public RuleUser(@Nullable Integer displayNumber) {
this(buildDefaultRule(displayNumber));
}
private static XvfbRule buildDefaultRule(@Nullable Integer displayNumber) {
if (displayNumber == null) {
return new XvfbRule();
} else {
return XvfbRule.builder().onDisplay(displayNumber.intValue()).build();
}
}
public RuleUser(XvfbRule xvfb) {
this.xvfb = checkNotNull(xvfb);
}
| // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/RuleUser.java
import com.github.mike10004.xvfbmanager.XvfbController;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
package com.github.mike10004.xvfbtesting;
abstract class RuleUser {
private final XvfbRule xvfb;
public RuleUser(@Nullable Integer displayNumber) {
this(buildDefaultRule(displayNumber));
}
private static XvfbRule buildDefaultRule(@Nullable Integer displayNumber) {
if (displayNumber == null) {
return new XvfbRule();
} else {
return XvfbRule.builder().onDisplay(displayNumber.intValue()).build();
}
}
public RuleUser(XvfbRule xvfb) {
this.xvfb = checkNotNull(xvfb);
}
| protected abstract void use(XvfbController ctrl) throws Exception; |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/EagerNoInvocationTest.java | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
| import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbtesting;
public class EagerNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireNotWindows();
@Rule
public final XvfbRule rule = XvfbRule.builder() | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/EagerNoInvocationTest.java
import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbtesting;
public class EagerNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireNotWindows();
@Rule
public final XvfbRule rule = XvfbRule.builder() | .manager(new ControllerCreationCountingManager(creationCalls)) |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_WindowsTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
| import com.github.mike10004.nativehelper.Platforms;
import com.github.mike10004.xvfbmanager.XvfbController;
import com.google.common.base.Suppliers;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*; | package com.github.mike10004.xvfbtesting;
@RunWith(Parameterized.class)
public class XvfbRule_WindowsTest {
private final XvfbRule rule;
public XvfbRule_WindowsTest(XvfbRule rule) {
this.rule = rule;
}
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireWindows();
@Parameterized.Parameters
public static List<XvfbRule> rules() {
return Arrays.asList(
XvfbRule.builder().build(),
XvfbRule.builder().eager().build(),
XvfbRule.builder().disabled().build(),
XvfbRule.builder().disabled(true).build(),
XvfbRule.builder().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().eager().disabled().build(),
XvfbRule.builder().eager().disabled(true).build(),
XvfbRule.builder().eager().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(true).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(Suppliers.ofInstance(true)).build()
);
}
@Test
public void testDisablingOnWindows() throws Exception {
System.out.format("rule = %s%n", rule);
new RuleUser(rule) {
@Override | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbController.java
// public interface XvfbController extends Closeable {
//
// String ENV_DISPLAY = "DISPLAY";
//
// /**
// * Waits until the display is ready, using default values for the polling
// * interval and maximum polls. Implementations may select the defaults
// * to use.
// * @throws InterruptedException if waiting is interrupted
// * @see #waitUntilReady(long, int)
// */
// void waitUntilReady() throws InterruptedException;
//
// /**
// * Waits until the X display is ready, polling at a given interval until the
// * display is ready or the given number of polls has been executed.
// * @param pollIntervalMs interval between polls in milliseconds
// * @param maxNumPolls maximum number of polls to execute
// * @throws InterruptedException if waiting is interrupted
// */
// void waitUntilReady(long pollIntervalMs, int maxNumPolls) throws InterruptedException;
//
// /**
// * Stops the virtual framebuffer process.
// */
// void stop();
//
// /**
// * Gets the display number in the format {@code :N} where {@code N} is the display number.
// * @return the display
// */
// String getDisplay();
//
// /**
// * Sets the display environment variable in the given environment.
// * @param environment map of environment variables in which display is to be set
// * @return the argument environment object
// * @see #ENV_DISPLAY
// */
// Map<String, String> configureEnvironment(Map<String, String> environment);
//
// /**
// * Creates a new, mutable environment variable map with the display variable set.
// * @return the new environment map
// * @see #configureEnvironment(Map)
// */
// @SuppressWarnings("unused")
// Map<String, String> newEnvironment();
//
// /**
// * Captures a screenshot of the virtual framebuffer.
// * @return the screenshot
// * @throws XvfbException if screenshooting goes awry
// */
// Screenshooter<?> getScreenshooter() throws XvfbException;
//
// /**
// * Class representing information about a window rendered by an X server.
// */
// class XWindow {
//
// /**
// * Window ID. This is commonly an integer in hexadecimal format, for example {@code 0x38ab0e}.
// */
// public final String id;
//
// /**
// * Window title. Null means the window has no title. The title may also
// * be empty, though that is not common.
// */
// public final @Nullable String title;
//
// /**
// * The line of output from which this window instance was parsed. This is a
// * line from {@code }
// */
// public final String line;
//
// /**
// * Constructs a new instance of the class.
// * @param id window id
// * @param title window title
// * @param line line of output from which this window information was parsed
// */
// public XWindow(String id, @Nullable String title, String line) {
// this.id = id;
// this.title = title;
// this.line = line;
// }
//
// @Override
// public String toString() {
// return "XWindow{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", length=" + (line == null ? -1 : line.length()) +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// XWindow xWindow = (XWindow) o;
//
// if (id != null ? !id.equals(xWindow.id) : xWindow.id != null) return false;
// if (title != null ? !title.equals(xWindow.title) : xWindow.title != null) return false;
// return line != null ? line.equals(xWindow.line) : xWindow.line == null;
// }
//
// @Override
// public int hashCode() {
// int result = id != null ? id.hashCode() : 0;
// result = 31 * result + (title != null ? title.hashCode() : 0);
// result = 31 * result + (line != null ? line.hashCode() : 0);
// return result;
// }
// }
//
// Optional<TreeNode<XWindow>> pollForWindow(Predicate<XWindow> windowFinder, long intervalMs, int maxPollAttempts) throws InterruptedException;
//
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/XvfbRule_WindowsTest.java
import com.github.mike10004.nativehelper.Platforms;
import com.github.mike10004.xvfbmanager.XvfbController;
import com.google.common.base.Suppliers;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
package com.github.mike10004.xvfbtesting;
@RunWith(Parameterized.class)
public class XvfbRule_WindowsTest {
private final XvfbRule rule;
public XvfbRule_WindowsTest(XvfbRule rule) {
this.rule = rule;
}
@ClassRule
public static PlatformRule platformRule = PlatformRule.requireWindows();
@Parameterized.Parameters
public static List<XvfbRule> rules() {
return Arrays.asList(
XvfbRule.builder().build(),
XvfbRule.builder().eager().build(),
XvfbRule.builder().disabled().build(),
XvfbRule.builder().disabled(true).build(),
XvfbRule.builder().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().eager().disabled().build(),
XvfbRule.builder().eager().disabled(true).build(),
XvfbRule.builder().eager().disabled(Suppliers.ofInstance(true)).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(true).build(),
XvfbRule.builder().notDisabledOnWindows().disabled(Suppliers.ofInstance(true)).build()
);
}
@Test
public void testDisablingOnWindows() throws Exception {
System.out.format("rule = %s%n", rule);
new RuleUser(rule) {
@Override | protected void use(XvfbController ctrl) throws Exception { |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XwdFileToPngConverter.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Screenshot.java
// class FileByteSource extends ByteSource {
//
// public final File file;
// private final ByteSource delegate;
//
// public FileByteSource(File file) {
// this(file, Files.asByteSource(file));
// }
//
// protected FileByteSource(File file, ByteSource delegate) {
// this.file = checkNotNull(file);
// this.delegate = checkNotNull(delegate);
// }
//
// @Override
// public CharSource asCharSource(Charset charset) {
// return delegate.asCharSource(charset);
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return delegate.openStream();
// }
//
// @Override
// public InputStream openBufferedStream() throws IOException {
// return delegate.openBufferedStream();
// }
//
// @Override
// public ByteSource slice(long offset, long length) {
// return delegate.slice(offset, length);
// }
//
// @Override
// public boolean isEmpty() throws IOException {
// return delegate.isEmpty();
// }
//
// @SuppressWarnings("Guava")
// @Override
// @Beta
// public com.google.common.base.Optional<Long> sizeIfKnown() {
// return delegate.sizeIfKnown();
// }
//
// @Override
// public long size() throws IOException {
// return delegate.size();
// }
//
// @Override
// public long copyTo(OutputStream output) throws IOException {
// return delegate.copyTo(output);
// }
//
// @Override
// public long copyTo(ByteSink sink) throws IOException {
// return delegate.copyTo(sink);
// }
//
// @Override
// public byte[] read() throws IOException {
// return delegate.read();
// }
//
// @Override
// @Beta
// public <T> T read(ByteProcessor<T> processor) throws IOException {
// return delegate.read(processor);
// }
//
// @Override
// public HashCode hash(HashFunction hashFunction) throws IOException {
// return delegate.hash(hashFunction);
// }
//
// @Override
// public boolean contentEquals(ByteSource other) throws IOException {
// return delegate.contentEquals(other);
// }
// }
| import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Screenshot.FileByteSource;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull; | this.processTracker = requireNonNull(processTracker);
}
@Override
public ImageioReadableScreenshot convert(Screenshot source) throws IOException, XvfbException {
File pnmFile = File.createTempFile("xwdtopnm-stdout", ".ppm", tempDir.toFile());
try {
return convert(source, pnmFile);
} finally {
if (!pnmFile.delete()) {
log.info("failed to delete {}", pnmFile);
}
}
}
protected ImageioReadableScreenshot convert(Screenshot source, File pnmFile) throws IOException, XvfbException {
File stderrFile = File.createTempFile("xwdtopnm-stderr", ".txt", tempDir.toFile());
try {
return convert(source, pnmFile, stderrFile);
} finally {
if (!stderrFile.delete()) {
log.info("failed to delete {}", stderrFile);
}
}
}
public ImageioReadableScreenshot convert(Screenshot source, File pnmFile, File stderrFile) throws IOException, XvfbException {
final File inputFile;
final boolean deleteInputFile;
ByteSource inputSource = source.asByteSource(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Screenshot.java
// class FileByteSource extends ByteSource {
//
// public final File file;
// private final ByteSource delegate;
//
// public FileByteSource(File file) {
// this(file, Files.asByteSource(file));
// }
//
// protected FileByteSource(File file, ByteSource delegate) {
// this.file = checkNotNull(file);
// this.delegate = checkNotNull(delegate);
// }
//
// @Override
// public CharSource asCharSource(Charset charset) {
// return delegate.asCharSource(charset);
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return delegate.openStream();
// }
//
// @Override
// public InputStream openBufferedStream() throws IOException {
// return delegate.openBufferedStream();
// }
//
// @Override
// public ByteSource slice(long offset, long length) {
// return delegate.slice(offset, length);
// }
//
// @Override
// public boolean isEmpty() throws IOException {
// return delegate.isEmpty();
// }
//
// @SuppressWarnings("Guava")
// @Override
// @Beta
// public com.google.common.base.Optional<Long> sizeIfKnown() {
// return delegate.sizeIfKnown();
// }
//
// @Override
// public long size() throws IOException {
// return delegate.size();
// }
//
// @Override
// public long copyTo(OutputStream output) throws IOException {
// return delegate.copyTo(output);
// }
//
// @Override
// public long copyTo(ByteSink sink) throws IOException {
// return delegate.copyTo(sink);
// }
//
// @Override
// public byte[] read() throws IOException {
// return delegate.read();
// }
//
// @Override
// @Beta
// public <T> T read(ByteProcessor<T> processor) throws IOException {
// return delegate.read(processor);
// }
//
// @Override
// public HashCode hash(HashFunction hashFunction) throws IOException {
// return delegate.hash(hashFunction);
// }
//
// @Override
// public boolean contentEquals(ByteSource other) throws IOException {
// return delegate.contentEquals(other);
// }
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XwdFileToPngConverter.java
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Screenshot.FileByteSource;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
this.processTracker = requireNonNull(processTracker);
}
@Override
public ImageioReadableScreenshot convert(Screenshot source) throws IOException, XvfbException {
File pnmFile = File.createTempFile("xwdtopnm-stdout", ".ppm", tempDir.toFile());
try {
return convert(source, pnmFile);
} finally {
if (!pnmFile.delete()) {
log.info("failed to delete {}", pnmFile);
}
}
}
protected ImageioReadableScreenshot convert(Screenshot source, File pnmFile) throws IOException, XvfbException {
File stderrFile = File.createTempFile("xwdtopnm-stderr", ".txt", tempDir.toFile());
try {
return convert(source, pnmFile, stderrFile);
} finally {
if (!stderrFile.delete()) {
log.info("failed to delete {}", stderrFile);
}
}
}
public ImageioReadableScreenshot convert(Screenshot source, File pnmFile, File stderrFile) throws IOException, XvfbException {
final File inputFile;
final boolean deleteInputFile;
ByteSource inputSource = source.asByteSource(); | if (inputSource instanceof FileByteSource) { |
mike10004/xvfb-manager-java | xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyNoInvocationTest.java | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
| import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbtesting;
/**
* Unit test that runs on all platforms. A lazy rule is created but {@link XvfbRule#getController()} is never
* invoked, so no attempt to execute an Xvfb process should be made.
*/
public class LazyNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@Rule
public final XvfbRule rule = XvfbRule.builder() | // Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyRuleTest.java
// static class ControllerCreationCountingManager extends XvfbManager {
// public final AtomicInteger controllerCreationCounter;
//
// public ControllerCreationCountingManager(AtomicInteger controllerCreationCounter) {
// this.controllerCreationCounter = controllerCreationCounter;
// }
//
// @Override
// protected DefaultXvfbController createController(ProcessMonitor<File, File> future, String display, File framebufferDir) {
// controllerCreationCounter.incrementAndGet();
// return super.createController(future, display, framebufferDir);
// }
// }
// Path: xvfb-testing/src/test/java/com/github/mike10004/xvfbtesting/LazyNoInvocationTest.java
import com.github.mike10004.xvfbtesting.LazyRuleTest.ControllerCreationCountingManager;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbtesting;
/**
* Unit test that runs on all platforms. A lazy rule is created but {@link XvfbRule#getController()} is never
* invoked, so no attempt to execute an Xvfb process should be made.
*/
public class LazyNoInvocationTest {
private final AtomicInteger creationCalls = new AtomicInteger();
@Rule
public final XvfbRule rule = XvfbRule.builder() | .manager(new ControllerCreationCountingManager(creationCalls)) |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Sleeper.java
// class DefaultSleeper implements Sleeper {
//
// private DefaultSleeper() {
// }
//
// private static final DefaultSleeper instance = new DefaultSleeper();
//
// /**
// * Gets the singleton instance of this class.
// * @return the singleton
// */
// public static DefaultSleeper getInstance() {
// return instance;
// }
//
// @Override
// public void sleep(long millis) throws InterruptedException {
// Thread.sleep(millis);
// }
// }
| import com.github.mike10004.xvfbmanager.Sleeper.DefaultSleeper;
import javax.annotation.Nullable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; | package com.github.mike10004.xvfbmanager;
/**
* Class that facilitates polling for an arbitrary condition. Polling is
* the act of repeatedly querying the state at defined intervals. Polling
* stops when this poller's {@link #check(int) evaluation function}
* answers with a reason to stop, or the iterator of intervals to wait
* between polls is exhausted. Reasons to stop include
* {@link PollAction#RESOLVE resolution}, meaning the poller is satisfied
* with the result, or {@link PollAction#ABORT abortion} meaning polling
* must stop early without a resolution.
*
* @param <T> type of content returned upon resolution
*/
public abstract class Poller<T> {
private final Sleeper sleeper;
/**
* Creates a new poller. The poller waits between polls using the
* default {@link Sleeper}. Subclasses can use an alternate sleeper,
* is helpful if you want to test your poller without actually waiting.
*/
public Poller() { | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Sleeper.java
// class DefaultSleeper implements Sleeper {
//
// private DefaultSleeper() {
// }
//
// private static final DefaultSleeper instance = new DefaultSleeper();
//
// /**
// * Gets the singleton instance of this class.
// * @return the singleton
// */
// public static DefaultSleeper getInstance() {
// return instance;
// }
//
// @Override
// public void sleep(long millis) throws InterruptedException {
// Thread.sleep(millis);
// }
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
import com.github.mike10004.xvfbmanager.Sleeper.DefaultSleeper;
import javax.annotation.Nullable;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
package com.github.mike10004.xvfbmanager;
/**
* Class that facilitates polling for an arbitrary condition. Polling is
* the act of repeatedly querying the state at defined intervals. Polling
* stops when this poller's {@link #check(int) evaluation function}
* answers with a reason to stop, or the iterator of intervals to wait
* between polls is exhausted. Reasons to stop include
* {@link PollAction#RESOLVE resolution}, meaning the poller is satisfied
* with the result, or {@link PollAction#ABORT abortion} meaning polling
* must stop early without a resolution.
*
* @param <T> type of content returned upon resolution
*/
public abstract class Poller<T> {
private final Sleeper sleeper;
/**
* Creates a new poller. The poller waits between polls using the
* default {@link Sleeper}. Subclasses can use an alternate sleeper,
* is helpful if you want to test your poller without actually waiting.
*/
public Poller() { | this(DefaultSleeper.getInstance()); |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull; | /*
* (c) 2016 Novetta
*
* Created by mike
*/
package com.github.mike10004.xvfbmanager;
public class PollingXLockFileChecker implements DefaultXvfbController.XLockFileChecker {
private final long pollIntervalMs;
private final Sleeper sleeper;
private final XLockFileUtility lockFileUtility;
public PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper) {
this(pollIntervalMs, sleeper, XLockFileUtility.getInstance());
}
@VisibleForTesting
PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper, XLockFileUtility lockFileUtility) {
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
/*
* (c) 2016 Novetta
*
* Created by mike
*/
package com.github.mike10004.xvfbmanager;
public class PollingXLockFileChecker implements DefaultXvfbController.XLockFileChecker {
private final long pollIntervalMs;
private final Sleeper sleeper;
private final XLockFileUtility lockFileUtility;
public PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper) {
this(pollIntervalMs, sleeper, XLockFileUtility.getInstance());
}
@VisibleForTesting
PollingXLockFileChecker(long pollIntervalMs, Sleeper sleeper, XLockFileUtility lockFileUtility) {
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis(); | PollOutcome<?> pollOutcome; |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull; | this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis();
PollOutcome<?> pollOutcome;
try {
pollOutcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
long now = System.currentTimeMillis();
if (now - startTime > timeoutMs) {
return abortPolling();
}
return lockFile.exists() ? continuePolling() : resolve(null);
}
}.poll(pollIntervalMs, maxNumPolls);
} catch (InterruptedException e) {
throw new LockFileCheckingException(e);
} | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/PollingXLockFileChecker.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import java.io.File;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
this.pollIntervalMs = pollIntervalMs;
this.sleeper = sleeper;
this.lockFileUtility = checkNotNull(lockFileUtility);
}
@Override
public void waitForCleanup(String display, long timeoutMs) throws LockFileCheckingException {
File lockFile;
try {
lockFile = lockFileUtility.constructLockFilePathname(display);
} catch (IOException e) {
throw new LockFileCheckingException(e);
}
int maxNumPolls = Ints.checkedCast(Math.round(Math.ceil((float) timeoutMs / (float) pollIntervalMs)));
long startTime = System.currentTimeMillis();
PollOutcome<?> pollOutcome;
try {
pollOutcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
long now = System.currentTimeMillis();
if (now - startTime > timeoutMs) {
return abortPolling();
}
return lockFile.exists() ? continuePolling() : resolve(null);
}
}.poll(pollIntervalMs, maxNumPolls);
} catch (InterruptedException e) {
throw new LockFileCheckingException(e);
} | if (pollOutcome.reason == StopReason.ABORTED || pollOutcome.reason == StopReason.TIMEOUT) { |
mike10004/xvfb-manager-java | xvfb-unittest-help/src/test/java/com/github/mike10004/xvfbunittesthelp/FatalAssumerTest.java | // Path: xvfb-unittest-help/src/main/java/com/github/mike10004/xvfbunittesthelp/FatalAssumer.java
// static class AssumptionViolatedError extends Error {
//
// public AssumptionViolatedError() {
// }
//
// public AssumptionViolatedError(String message) {
// super(message);
// }
//
// public AssumptionViolatedError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AssumptionViolatedError(Throwable cause) {
// super(cause);
// }
// }
| import com.github.mike10004.xvfbunittesthelp.FatalAssumer.AssumptionViolatedError;
import org.junit.Test;
import static org.junit.Assert.*; | package com.github.mike10004.xvfbunittesthelp;
public class FatalAssumerTest {
@Test
public void format() throws Exception {
String actual = FatalAssumer.format("hello %s", "world");
assertEquals("formatted", "hello world", actual);
}
@Test
public void assumeTrue_message() throws Exception {
String message = "hello world";
try {
new FatalAssumer().assumeTrue(message, false); | // Path: xvfb-unittest-help/src/main/java/com/github/mike10004/xvfbunittesthelp/FatalAssumer.java
// static class AssumptionViolatedError extends Error {
//
// public AssumptionViolatedError() {
// }
//
// public AssumptionViolatedError(String message) {
// super(message);
// }
//
// public AssumptionViolatedError(String message, Throwable cause) {
// super(message, cause);
// }
//
// public AssumptionViolatedError(Throwable cause) {
// super(cause);
// }
// }
// Path: xvfb-unittest-help/src/test/java/com/github/mike10004/xvfbunittesthelp/FatalAssumerTest.java
import com.github.mike10004.xvfbunittesthelp.FatalAssumer.AssumptionViolatedError;
import org.junit.Test;
import static org.junit.Assert.*;
package com.github.mike10004.xvfbunittesthelp;
public class FatalAssumerTest {
@Test
public void format() throws Exception {
String actual = FatalAssumer.format("hello %s", "world");
assertEquals("formatted", "hello world", actual);
}
@Test
public void assumeTrue_message() throws Exception {
String message = "hello world";
try {
new FatalAssumer().assumeTrue(message, false); | } catch (AssumptionViolatedError e) { |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull; | return true;
}
};
}
private static final long AUTO_DISPLAY_POLL_INTERVAL_MS = 100;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
}; | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java
import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
return true;
}
};
}
private static final long AUTO_DISPLAY_POLL_INTERVAL_MS = 100;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
}; | PollOutcome<Integer> pollOutcome; |
mike10004/xvfb-manager-java | xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull; | private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
};
PollOutcome<Integer> pollOutcome;
try {
pollOutcome = poller.poll(AUTO_DISPLAY_POLL_INTERVAL_MS, AUTO_DISPLAY_POLLS_MAX);
} catch (InterruptedException e) {
throw new XvfbException("interrupted while polling for display number", e);
} | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/XvfbManager.java
import com.github.mike10004.nativehelper.Whicher;
import com.google.common.util.concurrent.JdkFutureAdapters;
import io.github.mike10004.subprocess.ProcessMonitor;
import io.github.mike10004.subprocess.ProcessResult;
import io.github.mike10004.subprocess.ProcessTracker;
import io.github.mike10004.subprocess.Subprocess;
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.io.CharSource;
import com.google.common.io.Files;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import io.github.mike10004.subprocess.SubprocessLaunchSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
private static final int AUTO_DISPLAY_POLLS_MAX = 20;
protected int pollForDisplayNumber(final CharSource cs) {
Poller<Integer> poller = new Poller<Integer>() {
@Override
protected PollAnswer<Integer> check(int pollAttemptsSoFar) {
@Nullable String lastLine = null;
try {
lastLine = Iterables.getFirst(cs.readLines().reverse(), null);
} catch (IOException e) {
log.info("failed to read from {}", cs);
}
if (lastLine != null) {
lastLine = lastLine.trim();
if (lastLine.matches("\\d+")) {
int displayNumber = Integer.parseInt(lastLine);
return resolve(displayNumber);
} else {
log.debug("last line of xvfb output is not an integer: {}", StringUtils.abbreviate(lastLine, 128));
}
}
return continuePolling();
}
};
PollOutcome<Integer> pollOutcome;
try {
pollOutcome = poller.poll(AUTO_DISPLAY_POLL_INTERVAL_MS, AUTO_DISPLAY_POLLS_MAX);
} catch (InterruptedException e) {
throw new XvfbException("interrupted while polling for display number", e);
} | if (pollOutcome.reason == StopReason.RESOLVED) { |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | package com.github.mike10004.xvfbmanager;
public class PollerTest {
@Test
public void poll_immediatelyTrue() throws Exception { | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
package com.github.mike10004.xvfbmanager;
public class PollerTest {
@Test
public void poll_immediatelyTrue() throws Exception { | testPoller(0, 0, 1000, StopReason.TIMEOUT, 0); |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | testPoller(0, 100, 1000, StopReason.RESOLVED, 0);
}
@Test
public void poll_trueAfterOne() throws Exception {
testPoller(1, 100, 1000, StopReason.RESOLVED, 1000);
}
@Test
public void poll_notTrueBeforeLimit() throws Exception {
testPoller(5, 4, 1000, StopReason.TIMEOUT, 4000);
}
@Test
public void poll_abortFromCheck_0() throws Exception {
poll_abortFromCheck(0);
}
@Test
public void poll_abortFromCheck_1() throws Exception {
poll_abortFromCheck(1);
}
@Test
public void poll_abortFromCheck_2() throws Exception {
poll_abortFromCheck(2);
}
public void poll_abortFromCheck(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
testPoller(0, 100, 1000, StopReason.RESOLVED, 0);
}
@Test
public void poll_trueAfterOne() throws Exception {
testPoller(1, 100, 1000, StopReason.RESOLVED, 1000);
}
@Test
public void poll_notTrueBeforeLimit() throws Exception {
testPoller(5, 4, 1000, StopReason.TIMEOUT, 4000);
}
@Test
public void poll_abortFromCheck_0() throws Exception {
poll_abortFromCheck(0);
}
@Test
public void poll_abortFromCheck_1() throws Exception {
poll_abortFromCheck(1);
}
@Test
public void poll_abortFromCheck_2() throws Exception {
poll_abortFromCheck(2);
}
public void poll_abortFromCheck(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper(); | PollOutcome<?> outcome = new Poller<Void>(sleeper) { |
mike10004/xvfb-manager-java | xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
| import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals; | public void poll_timeoutOverridesAbort(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper();
PollOutcome<?> outcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
return pollAttemptsSoFar >= attempts ? abortPolling() : continuePolling();
}
}.poll(1000, attempts); // poll forever
assertEquals("reason", StopReason.TIMEOUT, outcome.reason);
assertEquals("duration", attempts * 1000, sleeper.getDuration());
assertEquals("sleep count", attempts, sleeper.getCount());
}
@Test(expected = IllegalArgumentException.class)
public void poll_badArgs() throws Exception {
testPoller(5, 4, -1000, null, 0);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_1() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 1, StopReason.TIMEOUT, 1000, 1);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_2() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 2, StopReason.TIMEOUT, 2000, 2);
}
public void testDoNotSleepIfAboutToTimeOut(long intervalMs, int maxPolls, StopReason stopReason, long expectedDuration, int expectedSleeps) throws Exception {
TestSleeper sleeper = new TestSleeper(); | // Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public static class PollOutcome<E> {
//
// /**
// * Reason polling stopped.
// */
// public final StopReason reason;
//
// /**
// * An object that represents the resolved state of the poll.
// */
// public final @Nullable E content;
//
// /**
// * Gets the polling duration. This may not be exact.
// */
// public final Duration duration;
//
// private final int numAttempts;
//
// private PollOutcome(StopReason reason, @Nullable E content, Duration duration, int numAttempts) {
// this.reason = checkNotNull(reason);
// this.content = content;
// this.duration = checkNotNull(duration);
// this.numAttempts = numAttempts;
// }
//
// @Override
// public String toString() {
// return "PollOutcome{" +
// "reason=" + reason +
// ", content=" + content +
// ", duration=" + duration +
// ", attempts=" + numAttempts +
// '}';
// }
//
// /**
// * Gets the number of times the poll was attempted. This is the numbef of
// * times the {@link #check(int) check()} function is invoked.
// * @return count of attempts
// */
// public int getNumAttempts() {
// return numAttempts;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// PollOutcome<?> that = (PollOutcome<?>) o;
//
// if (numAttempts != that.numAttempts) return false;
// if (reason != that.reason) return false;
// if (content != null ? !content.equals(that.content) : that.content != null) return false;
// return duration.equals(that.duration);
// }
//
// @Override
// public int hashCode() {
// int result = reason.hashCode();
// result = 31 * result + (content != null ? content.hashCode() : 0);
// result = 31 * result + duration.hashCode();
// result = 31 * result + numAttempts;
// return result;
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// protected static class SimplePoller extends Poller<Void> {
//
// private final Supplier<Boolean> condition;
//
// public SimplePoller(Sleeper sleeper, Supplier<Boolean> condition) {
// super(sleeper);
// this.condition = checkNotNull(condition);
// }
//
// public SimplePoller(Supplier<Boolean> condition) {
// super();
// this.condition = checkNotNull(condition);
// }
//
// @Override
// protected PollAnswer<Void> check(int pollAttemptsSoFar) {
// boolean state = condition.get();
// if (state) {
// return resolve(null);
// } else {
// return continuePolling();
// }
// }
// }
//
// Path: xvfb-manager/src/main/java/com/github/mike10004/xvfbmanager/Poller.java
// public enum StopReason {
//
// /**
// * State was resolved to the poller's satisfaction.
// */
// RESOLVED,
//
// /**
// * State was not resolved to the poller's satisfaction,
// * but polling must cease anyway.
// */
// ABORTED,
//
// /**
// * The poller's iterator of intervals was exhausted
// * prior to resolution or abortion of polling.
// */
// TIMEOUT
// }
// Path: xvfb-manager/src/test/java/com/github/mike10004/xvfbmanager/PollerTest.java
import com.github.mike10004.xvfbmanager.Poller.PollOutcome;
import com.github.mike10004.xvfbmanager.Poller.SimplePoller;
import com.github.mike10004.xvfbmanager.Poller.StopReason;
import com.google.common.base.Suppliers;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.Assert.assertEquals;
public void poll_timeoutOverridesAbort(final int attempts) throws Exception {
TestSleeper sleeper = new TestSleeper();
PollOutcome<?> outcome = new Poller<Void>(sleeper) {
@Override
protected PollAnswer<Void> check(int pollAttemptsSoFar) {
return pollAttemptsSoFar >= attempts ? abortPolling() : continuePolling();
}
}.poll(1000, attempts); // poll forever
assertEquals("reason", StopReason.TIMEOUT, outcome.reason);
assertEquals("duration", attempts * 1000, sleeper.getDuration());
assertEquals("sleep count", attempts, sleeper.getCount());
}
@Test(expected = IllegalArgumentException.class)
public void poll_badArgs() throws Exception {
testPoller(5, 4, -1000, null, 0);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_1() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 1, StopReason.TIMEOUT, 1000, 1);
}
@Test
public void testDoNotSleepIfAboutToTimeOut_2() throws Exception {
testDoNotSleepIfAboutToTimeOut(1000, 2, StopReason.TIMEOUT, 2000, 2);
}
public void testDoNotSleepIfAboutToTimeOut(long intervalMs, int maxPolls, StopReason stopReason, long expectedDuration, int expectedSleeps) throws Exception {
TestSleeper sleeper = new TestSleeper(); | PollOutcome<Void> outcome = new SimplePoller(sleeper, Suppliers.ofInstance(false)).poll(intervalMs, maxPolls); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/data/article/ArticleShare.java | // Path: src/main/java/me/hao0/wechat/serializer/ArticleShareSceneDeserializer.java
// public class ArticleShareSceneDeserializer extends JsonDeserializer<ArticleShareScene> {
//
// @Override
// public ArticleShareScene deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return ArticleShareScene.from(parser.getIntValue());
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.ArticleShareSceneDeserializer;
import java.io.Serializable; | package me.hao0.wechat.model.data.article;
/**
* 图文分享转发数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class ArticleShare implements Serializable {
private static final long serialVersionUID = -2590968439236572137L;
/**
* 日期
*/
@JsonProperty("ref_date")
private String date;
/**
* 分享场景
*/
@JsonProperty("share_scene") | // Path: src/main/java/me/hao0/wechat/serializer/ArticleShareSceneDeserializer.java
// public class ArticleShareSceneDeserializer extends JsonDeserializer<ArticleShareScene> {
//
// @Override
// public ArticleShareScene deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return ArticleShareScene.from(parser.getIntValue());
// }
// }
// Path: src/main/java/me/hao0/wechat/model/data/article/ArticleShare.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.ArticleShareSceneDeserializer;
import java.io.Serializable;
package me.hao0.wechat.model.data.article;
/**
* 图文分享转发数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class ArticleShare implements Serializable {
private static final long serialVersionUID = -2590968439236572137L;
/**
* 日期
*/
@JsonProperty("ref_date")
private String date;
/**
* 分享场景
*/
@JsonProperty("share_scene") | @JsonDeserialize(using = ArticleShareSceneDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/event/RecvEvent.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessage.java
// public class RecvMessage implements Serializable {
//
// /**
// * 开发者微信号
// */
// protected String toUserName;
//
// /**
// * 用户openId
// */
// protected String fromUserName;
//
// /**
// * 消息创建时间
// */
// protected Integer createTime;
//
// /**
// * 消息类型:
// * @see me.hao0.wechat.model.message.resp.RespMessageType
// */
// protected String msgType;
//
// public RecvMessage(){}
//
// public RecvMessage(RecvMessage m){
// this.toUserName = m.toUserName;
// this.fromUserName = m.fromUserName;
// this.createTime = m.createTime;
// this.msgType = m.msgType;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public Integer getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(Integer createTime) {
// this.createTime = createTime;
// }
//
// public void setMsgType(String msgType) {
// this.msgType = msgType;
// }
//
// public String getMsgType(){
// return this.msgType;
// }
//
// @Override
// public String toString() {
// return "RecvMessage{" +
// "toUserName='" + toUserName + '\'' +
// ", fromUserName='" + fromUserName + '\'' +
// ", createTime=" + createTime +
// ", msgType='" + msgType + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessage;
import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.event;
/**
* 接收微信服务器的事件消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvEvent extends RecvMessage {
/**
* 事件类型:
* @see RecvEvent
*/
protected String eventType;
public RecvEvent(){}
public RecvEvent(RecvMessage e){
super(e);
}
public void setEventType(String eventType){
this.eventType = eventType;
}
public String getEventType(){
return this.eventType;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessage.java
// public class RecvMessage implements Serializable {
//
// /**
// * 开发者微信号
// */
// protected String toUserName;
//
// /**
// * 用户openId
// */
// protected String fromUserName;
//
// /**
// * 消息创建时间
// */
// protected Integer createTime;
//
// /**
// * 消息类型:
// * @see me.hao0.wechat.model.message.resp.RespMessageType
// */
// protected String msgType;
//
// public RecvMessage(){}
//
// public RecvMessage(RecvMessage m){
// this.toUserName = m.toUserName;
// this.fromUserName = m.fromUserName;
// this.createTime = m.createTime;
// this.msgType = m.msgType;
// }
//
// public String getToUserName() {
// return toUserName;
// }
//
// public void setToUserName(String toUserName) {
// this.toUserName = toUserName;
// }
//
// public String getFromUserName() {
// return fromUserName;
// }
//
// public void setFromUserName(String fromUserName) {
// this.fromUserName = fromUserName;
// }
//
// public Integer getCreateTime() {
// return createTime;
// }
//
// public void setCreateTime(Integer createTime) {
// this.createTime = createTime;
// }
//
// public void setMsgType(String msgType) {
// this.msgType = msgType;
// }
//
// public String getMsgType(){
// return this.msgType;
// }
//
// @Override
// public String toString() {
// return "RecvMessage{" +
// "toUserName='" + toUserName + '\'' +
// ", fromUserName='" + fromUserName + '\'' +
// ", createTime=" + createTime +
// ", msgType='" + msgType + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/event/RecvEvent.java
import me.hao0.wechat.model.message.receive.RecvMessage;
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.event;
/**
* 接收微信服务器的事件消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvEvent extends RecvMessage {
/**
* 事件类型:
* @see RecvEvent
*/
protected String eventType;
public RecvEvent(){}
public RecvEvent(RecvMessage e){
super(e);
}
public void setEventType(String eventType){
this.eventType = eventType;
}
public String getEventType(){
return this.eventType;
}
@Override
public String getMsgType() { | return RecvMessageType.EVENT.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/Menus.java | // Path: src/main/java/me/hao0/wechat/model/menu/Menu.java
// public class Menu implements Serializable {
//
// private static final long serialVersionUID = 3569890088693211989L;
//
// /**
// * 名称:
// * 一级最多4个字,二级最多7个字
// */
// private String name;
//
// /**
// * 类型
// */
// private String type;
//
// /**
// * 菜单key,当type="click"时
// */
// private String key;
//
// /**
// * 菜单url,当type="view"时
// */
// private String url;
//
// /**
// * 最多3个一级,5个二级
// */
// @JsonProperty("sub_button")
// private List<Menu> children = new ArrayList<>();
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public List<Menu> getChildren() {
// return children;
// }
//
// public void setChildren(List<Menu> children) {
// this.children = children;
// }
//
// @Override
// public String toString() {
// return "Menu{" +
// "name='" + name + '\'' +
// ", type='" + type + '\'' +
// ", key='" + key + '\'' +
// ", url='" + url + '\'' +
// ", children=" + children +
// '}';
// }
// }
| import com.fasterxml.jackson.databind.JavaType;
import me.hao0.wechat.model.menu.Menu;
import me.hao0.common.json.Jsons;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*; | package me.hao0.wechat.core;
/**
* 菜单组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class Menus extends Component {
/**
* 查询菜单
*/
private static final String GET = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
/**
* 创建菜单
*/
private static final String CREATE = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
/**
* 删除菜单
*/
private static final String DELETE = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
| // Path: src/main/java/me/hao0/wechat/model/menu/Menu.java
// public class Menu implements Serializable {
//
// private static final long serialVersionUID = 3569890088693211989L;
//
// /**
// * 名称:
// * 一级最多4个字,二级最多7个字
// */
// private String name;
//
// /**
// * 类型
// */
// private String type;
//
// /**
// * 菜单key,当type="click"时
// */
// private String key;
//
// /**
// * 菜单url,当type="view"时
// */
// private String url;
//
// /**
// * 最多3个一级,5个二级
// */
// @JsonProperty("sub_button")
// private List<Menu> children = new ArrayList<>();
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public List<Menu> getChildren() {
// return children;
// }
//
// public void setChildren(List<Menu> children) {
// this.children = children;
// }
//
// @Override
// public String toString() {
// return "Menu{" +
// "name='" + name + '\'' +
// ", type='" + type + '\'' +
// ", key='" + key + '\'' +
// ", url='" + url + '\'' +
// ", children=" + children +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/core/Menus.java
import com.fasterxml.jackson.databind.JavaType;
import me.hao0.wechat.model.menu.Menu;
import me.hao0.common.json.Jsons;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*;
package me.hao0.wechat.core;
/**
* 菜单组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class Menus extends Component {
/**
* 查询菜单
*/
private static final String GET = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
/**
* 创建菜单
*/
private static final String CREATE = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
/**
* 删除菜单
*/
private static final String DELETE = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
| private static final JavaType ARRAY_LIST_MENU_TYPE = Jsons.DEFAULT.createCollectionType(ArrayList.class, Menu.class); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvVideoMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 视频消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvVideoMessage extends RecvMsg {
private static final long serialVersionUID = -3750491257934605285L;
/**
* 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
/**
* 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String thumbMediaId;
public RecvVideoMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getThumbMediaId() {
return thumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
this.thumbMediaId = thumbMediaId;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvVideoMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 视频消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvVideoMessage extends RecvMsg {
private static final long serialVersionUID = -3750491257934605285L;
/**
* 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
/**
* 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String thumbMediaId;
public RecvVideoMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getThumbMediaId() {
return thumbMediaId;
}
public void setThumbMediaId(String thumbMediaId) {
this.thumbMediaId = thumbMediaId;
}
@Override
public String getMsgType() { | return RecvMessageType.VIDEO.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java | // Path: src/main/java/me/hao0/wechat/model/base/AccessToken.java
// public class AccessToken implements Serializable {
//
// private static final long serialVersionUID = 6038499458891708844L;
//
// /**
// * accessToken
// */
// private String accessToken;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expiredAt;
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpiredAt() {
// return expiredAt;
// }
//
// public void setExpiredAt(Long expiredAt) {
// this.expiredAt = expiredAt;
// }
//
// @Override
// public String toString() {
// return "AccessToken{" +
// "accessToken='" + accessToken + '\'' +
// ", expire=" + expire +
// ", expiredAt=" + expiredAt +
// '}';
// }
// }
| import me.hao0.wechat.model.base.AccessToken; | package me.hao0.wechat.loader;
/**
* accessToken加载接口
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 10/11/15
* @since 1.3.0
*/
public interface AccessTokenLoader {
/**
* 获取accessToken
* @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
*/
String get();
/**
* 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
* @param token 从微信服务器获取AccessToken
*/ | // Path: src/main/java/me/hao0/wechat/model/base/AccessToken.java
// public class AccessToken implements Serializable {
//
// private static final long serialVersionUID = 6038499458891708844L;
//
// /**
// * accessToken
// */
// private String accessToken;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expiredAt;
//
// public String getAccessToken() {
// return accessToken;
// }
//
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpiredAt() {
// return expiredAt;
// }
//
// public void setExpiredAt(Long expiredAt) {
// this.expiredAt = expiredAt;
// }
//
// @Override
// public String toString() {
// return "AccessToken{" +
// "accessToken='" + accessToken + '\'' +
// ", expire=" + expire +
// ", expiredAt=" + expiredAt +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java
import me.hao0.wechat.model.base.AccessToken;
package me.hao0.wechat.loader;
/**
* accessToken加载接口
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 10/11/15
* @since 1.3.0
*/
public interface AccessTokenLoader {
/**
* 获取accessToken
* @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
*/
String get();
/**
* 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
* @param token 从微信服务器获取AccessToken
*/ | void refresh(AccessToken token); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/data/msg/MsgSendSummary.java | // Path: src/main/java/me/hao0/wechat/serializer/MsgTypeDeserializer.java
// public class MsgTypeDeserializer extends JsonDeserializer<MsgType> {
//
// @Override
// public MsgType deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return MsgType.from(parser.getIntValue());
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.MsgTypeDeserializer;
import java.io.Serializable; | package me.hao0.wechat.model.data.msg;
/**
* 消息发送分析
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class MsgSendSummary implements Serializable {
private static final long serialVersionUID = -8877051363122800450L;
/**
* 日期
*/
@JsonProperty("ref_date")
private String date;
/**
* 消息类型
*/
@JsonProperty("msg_type") | // Path: src/main/java/me/hao0/wechat/serializer/MsgTypeDeserializer.java
// public class MsgTypeDeserializer extends JsonDeserializer<MsgType> {
//
// @Override
// public MsgType deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return MsgType.from(parser.getIntValue());
// }
// }
// Path: src/main/java/me/hao0/wechat/model/data/msg/MsgSendSummary.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.MsgTypeDeserializer;
import java.io.Serializable;
package me.hao0.wechat.model.data.msg;
/**
* 消息发送分析
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class MsgSendSummary implements Serializable {
private static final long serialVersionUID = -8877051363122800450L;
/**
* 日期
*/
@JsonProperty("ref_date")
private String date;
/**
* 消息类型
*/
@JsonProperty("msg_type") | @JsonDeserialize(using = MsgTypeDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvLinkMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 链接消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvLinkMessage extends RecvMsg {
private static final long serialVersionUID = -8070100690774814611L;
/**
* 消息标题
*/
private String title;
/**
* 消息描述
*/
private String description;
/**
* 消息链接
*/
private String url;
public RecvLinkMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvLinkMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 链接消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvLinkMessage extends RecvMsg {
private static final long serialVersionUID = -8070100690774814611L;
/**
* 消息标题
*/
private String title;
/**
* 消息描述
*/
private String description;
/**
* 消息链接
*/
private String url;
public RecvLinkMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String getMsgType() { | return RecvMessageType.LINK.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvShortVideoMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 小视频消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvShortVideoMessage extends RecvVideoMessage {
private static final long serialVersionUID = 4589295453710532536L;
public RecvShortVideoMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvShortVideoMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 小视频消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvShortVideoMessage extends RecvVideoMessage {
private static final long serialVersionUID = 4589295453710532536L;
public RecvShortVideoMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
@Override
public String getMsgType() { | return RecvMessageType.SHORT_VIDEO.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/loader/TicketLoader.java | // Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
| import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType; | package me.hao0.wechat.loader;
/**
* 凭证加载器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 15/11/15
* @since 1.3.0
*/
public interface TicketLoader {
/**
* 获取Ticket
* @param type ticket类型
* @see me.hao0.wechat.model.js.TicketType
* @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
*/
String get(TicketType type);
/**
* 刷新Ticket
* @param ticket 最新获取到的Ticket
*/ | // Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
// Path: src/main/java/me/hao0/wechat/loader/TicketLoader.java
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
package me.hao0.wechat.loader;
/**
* 凭证加载器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 15/11/15
* @since 1.3.0
*/
public interface TicketLoader {
/**
* 获取Ticket
* @param type ticket类型
* @see me.hao0.wechat.model.js.TicketType
* @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
*/
String get(TicketType type);
/**
* 刷新Ticket
* @param ticket 最新获取到的Ticket
*/ | void refresh(Ticket ticket); |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/JsSdks.java | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*; | package me.hao0.wechat.core;
/**
* JS-SDK组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class JsSdks extends Component {
/**
* 获取Ticket
*/
private static final String TICKET_GET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";
JsSdks(){}
/**
* 获取临时凭证
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @param cb 回调
*/ | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
// Path: src/main/java/me/hao0/wechat/core/JsSdks.java
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*;
package me.hao0.wechat.core;
/**
* JS-SDK组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class JsSdks extends Component {
/**
* 获取Ticket
*/
private static final String TICKET_GET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";
JsSdks(){}
/**
* 获取临时凭证
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @param cb 回调
*/ | public void getTicket(final TicketType type, final Callback<Ticket> cb){ |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/JsSdks.java | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*; | package me.hao0.wechat.core;
/**
* JS-SDK组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class JsSdks extends Component {
/**
* 获取Ticket
*/
private static final String TICKET_GET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";
JsSdks(){}
/**
* 获取临时凭证
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @param cb 回调
*/ | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
// Path: src/main/java/me/hao0/wechat/core/JsSdks.java
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*;
package me.hao0.wechat.core;
/**
* JS-SDK组件
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 18/11/15
* @since 1.4.0
*/
public final class JsSdks extends Component {
/**
* 获取Ticket
*/
private static final String TICKET_GET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";
JsSdks(){}
/**
* 获取临时凭证
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @param cb 回调
*/ | public void getTicket(final TicketType type, final Callback<Ticket> cb){ |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/JsSdks.java | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*; |
/**
* 获取临时凭证
* @param accessToken accessToken
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @return Ticket对象,或抛WechatException
*/
public Ticket getTicket(String accessToken, TicketType type){
checkNotNullAndEmpty(accessToken, "accessToken");
checkNotNull(type, "ticket type can't be null");
String url = TICKET_GET + accessToken + "&type=" + type.type();
Map<String, Object> resp = doGet(url);
Ticket t = new Ticket();
t.setTicket((String)resp.get("ticket"));
Integer expire = (Integer)resp.get("expires_in");
t.setExpire(expire);
t.setExpireAt(System.currentTimeMillis() + expire * 1000);
t.setType(type);
return t;
}
/**
* 获取JSSDK配置信息
* @param nonStr 随机字符串
* @param url 调用JSSDK的页面URL全路径(去除#后的)
* @return Config对象
*/ | // Path: src/main/java/me/hao0/wechat/model/js/Config.java
// public class Config implements Serializable {
//
// private static final long serialVersionUID = -8263857663686622616L;
//
// /**
// * 微信APP ID
// */
// private String appId;
//
// /**
// * 时间戳(秒)
// */
// private Long timestamp;
//
// /**
// * 随机字符串
// */
// private String nonStr;
//
// /**
// * 签名
// */
// private String signature;
//
// public Config(String appId, Long timestamp, String nonStr, String signature) {
// this.appId = appId;
// this.timestamp = timestamp;
// this.nonStr = nonStr;
// this.signature = signature;
// }
//
// public Config() {
// }
//
// public String getAppId() {
// return appId;
// }
//
// public void setAppId(String appId) {
// this.appId = appId;
// }
//
// public Long getTimestamp() {
// return timestamp;
// }
//
// public void setTimestamp(Long timestamp) {
// this.timestamp = timestamp;
// }
//
// public String getNonStr() {
// return nonStr;
// }
//
// public void setNonStr(String nonStr) {
// this.nonStr = nonStr;
// }
//
// public String getSignature() {
// return signature;
// }
//
// public void setSignature(String signature) {
// this.signature = signature;
// }
//
// @Override
// public String toString() {
// return "Config{" +
// "appId='" + appId + '\'' +
// ", timestamp=" + timestamp +
// ", nonStr='" + nonStr + '\'' +
// ", signature='" + signature + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/Ticket.java
// public class Ticket implements Serializable {
//
// private static final long serialVersionUID = 978451551258121101L;
//
// /**
// * 凭证字符串
// */
// private String ticket;
//
// /**
// * 凭证类型
// */
// private TicketType type;
//
// /**
// * 有效时间(s)
// */
// private Integer expire;
//
// /**
// * 过期时刻(ms)
// */
// private Long expireAt;
//
// public String getTicket() {
// return ticket;
// }
//
// public void setTicket(String ticket) {
// this.ticket = ticket;
// }
//
// public TicketType getType() {
// return type;
// }
//
// public void setType(TicketType type) {
// this.type = type;
// }
//
// public Integer getExpire() {
// return expire;
// }
//
// public void setExpire(Integer expire) {
// this.expire = expire;
// }
//
// public Long getExpireAt() {
// return expireAt;
// }
//
// public void setExpireAt(Long expireAt) {
// this.expireAt = expireAt;
// }
//
// @Override
// public String toString() {
// return "Ticket{" +
// "ticket='" + ticket + '\'' +
// ", type=" + type +
// ", expire=" + expire +
// ", expireAt=" + expireAt +
// '}';
// }
// }
//
// Path: src/main/java/me/hao0/wechat/model/js/TicketType.java
// public enum TicketType {
//
// /**
// * 用于调用微信JSSDK的临时票据
// */
// JSAPI("jsapi"),
//
// /**
// * 用于调用卡券相关接口的临时票据
// */
// CARD("wx_card");
//
// private String type;
//
// private TicketType(String type){
// this.type = type;
// }
//
// public String type(){
// return type;
// }
// }
// Path: src/main/java/me/hao0/wechat/core/JsSdks.java
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import me.hao0.wechat.model.js.Config;
import me.hao0.wechat.model.js.Ticket;
import me.hao0.wechat.model.js.TicketType;
import java.util.Map;
import static me.hao0.common.util.Preconditions.*;
/**
* 获取临时凭证
* @param accessToken accessToken
* @param type 凭证类型
* @see me.hao0.wechat.model.js.TicketType
* @return Ticket对象,或抛WechatException
*/
public Ticket getTicket(String accessToken, TicketType type){
checkNotNullAndEmpty(accessToken, "accessToken");
checkNotNull(type, "ticket type can't be null");
String url = TICKET_GET + accessToken + "&type=" + type.type();
Map<String, Object> resp = doGet(url);
Ticket t = new Ticket();
t.setTicket((String)resp.get("ticket"));
Integer expire = (Integer)resp.get("expires_in");
t.setExpire(expire);
t.setExpireAt(System.currentTimeMillis() + expire * 1000);
t.setType(type);
return t;
}
/**
* 获取JSSDK配置信息
* @param nonStr 随机字符串
* @param url 调用JSSDK的页面URL全路径(去除#后的)
* @return Config对象
*/ | public Config getConfig(String nonStr, String url){ |
ihaolin/wechat | src/main/java/me/hao0/wechat/utils/XmlWriters.java | // Path: src/main/java/me/hao0/wechat/exception/XmlException.java
// public class XmlException extends RuntimeException {
//
// public XmlException() {
// super();
// }
//
// public XmlException(String message) {
// super(message);
// }
//
// public XmlException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public XmlException(Throwable cause) {
// super(cause);
// }
//
// protected XmlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
| import me.hao0.wechat.exception.XmlException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | package me.hao0.wechat.utils;
/**
* 一个简陋的微信XML构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 6/11/15
*/
public class XmlWriters {
List<E> es = new ArrayList<>();
private XmlWriters(){}
public static XmlWriters create(){
return new XmlWriters();
}
public XmlWriters element(String name, String text){
E e = new TextE(name, text);
es.add(e);
return this;
}
public XmlWriters element(String name, Number number){
E e = new NumberE(name, number);
es.add(e);
return this;
}
public XmlWriters element(String parentName, String childName, String childText){
return element(parentName, new TextE(childName, childText));
}
public XmlWriters element(String parentName, String childName, Number childNumber){
return element(parentName, new NumberE(childName, childNumber));
}
/**
* 构建包含多个子元素的元素
* @param parentName 父元素标签名
* @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
* @return this
*/
public XmlWriters element(String parentName, Object... childPairs){
if (childPairs.length % 2 != 0){ | // Path: src/main/java/me/hao0/wechat/exception/XmlException.java
// public class XmlException extends RuntimeException {
//
// public XmlException() {
// super();
// }
//
// public XmlException(String message) {
// super(message);
// }
//
// public XmlException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public XmlException(Throwable cause) {
// super(cause);
// }
//
// protected XmlException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
// Path: src/main/java/me/hao0/wechat/utils/XmlWriters.java
import me.hao0.wechat.exception.XmlException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
package me.hao0.wechat.utils;
/**
* 一个简陋的微信XML构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 6/11/15
*/
public class XmlWriters {
List<E> es = new ArrayList<>();
private XmlWriters(){}
public static XmlWriters create(){
return new XmlWriters();
}
public XmlWriters element(String name, String text){
E e = new TextE(name, text);
es.add(e);
return this;
}
public XmlWriters element(String name, Number number){
E e = new NumberE(name, number);
es.add(e);
return this;
}
public XmlWriters element(String parentName, String childName, String childText){
return element(parentName, new TextE(childName, childText));
}
public XmlWriters element(String parentName, String childName, Number childNumber){
return element(parentName, new NumberE(childName, childNumber));
}
/**
* 构建包含多个子元素的元素
* @param parentName 父元素标签名
* @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
* @return this
*/
public XmlWriters element(String parentName, Object... childPairs){
if (childPairs.length % 2 != 0){ | throw new XmlException("var args's length must % 2 = 0"); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvTextMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 文本消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvTextMessage extends RecvMsg {
private static final long serialVersionUID = -8070100690774814611L;
/**
* 文本内容
*/
private String content;
public RecvTextMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvTextMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 文本消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvTextMessage extends RecvMsg {
private static final long serialVersionUID = -8070100690774814611L;
/**
* 文本内容
*/
private String content;
public RecvTextMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String getMsgType() { | return RecvMessageType.TEXT.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/user/User.java | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date; | package me.hao0.wechat.model.user;
/**
* 用户信息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 7/11/15
*/
public class User implements Serializable {
/**
* 0未关注,1已关注
*/
private Integer subscribe;
@JsonProperty("openid")
private String openId;
@JsonProperty("nickname")
private String nickName;
/**
* 0未知,1男,2女
*/
private Integer sex;
private String city;
private String province;
private String country;
@JsonProperty("headimgurl")
private String headImgUrl;
@JsonProperty("subscribe_time") | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
// Path: src/main/java/me/hao0/wechat/model/user/User.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date;
package me.hao0.wechat.model.user;
/**
* 用户信息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 7/11/15
*/
public class User implements Serializable {
/**
* 0未关注,1已关注
*/
private Integer subscribe;
@JsonProperty("openid")
private String openId;
@JsonProperty("nickname")
private String nickName;
/**
* 0未知,1男,2女
*/
private Integer sex;
private String city;
private String province;
private String country;
@JsonProperty("headimgurl")
private String headImgUrl;
@JsonProperty("subscribe_time") | @JsonDeserialize(using = DateDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvLocationMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 地理位置消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvLocationMessage extends RecvMsg {
private static final long serialVersionUID = 2468731105380952027L;
/**
* 纬度
*/
private String locationX;
/**
* 经度
*/
private String locationY;
/**
* 缩放大小
*/
private Integer scale;
/**
* 位置信息
*/
private String label;
public RecvLocationMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvLocationMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 地理位置消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvLocationMessage extends RecvMsg {
private static final long serialVersionUID = 2468731105380952027L;
/**
* 纬度
*/
private String locationX;
/**
* 经度
*/
private String locationY;
/**
* 缩放大小
*/
private Integer scale;
/**
* 位置信息
*/
private String label;
public RecvLocationMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
@Override
public String getMsgType() { | return RecvMessageType.LOCATION.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/material/TempMaterial.java | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date; | package me.hao0.wechat.model.material;
/**
* 上传临时素材后的返回对象
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 13/11/15
*/
public class TempMaterial implements Serializable {
private static final long serialVersionUID = -824128825701922924L;
private MaterialUploadType type;
@JsonProperty("media_id")
private String mediaId;
@JsonProperty("created_at") | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
// Path: src/main/java/me/hao0/wechat/model/material/TempMaterial.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date;
package me.hao0.wechat.model.material;
/**
* 上传临时素材后的返回对象
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 13/11/15
*/
public class TempMaterial implements Serializable {
private static final long serialVersionUID = -824128825701922924L;
private MaterialUploadType type;
@JsonProperty("media_id")
private String mediaId;
@JsonProperty("created_at") | @JsonDeserialize(using = DateDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvImageMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 图片消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvImageMessage extends RecvMsg {
private static final long serialVersionUID = 3465602607733657276L;
/**
* 图片链接
*/
private String picUrl;
/**
* 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
public RecvImageMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvImageMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 图片消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvImageMessage extends RecvMsg {
private static final long serialVersionUID = 3465602607733657276L;
/**
* 图片链接
*/
private String picUrl;
/**
* 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
public RecvImageMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
@Override
public String getMsgType() { | return RecvMessageType.IMAGE.value(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/data/user/UserSummary.java | // Path: src/main/java/me/hao0/wechat/serializer/UserSourceDeserializer.java
// public class UserSourceDeserializer extends JsonDeserializer<UserSource> {
//
// @Override
// public UserSource deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return UserSource.from(parser.getIntValue());
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.UserSourceDeserializer;
import java.io.Serializable; | package me.hao0.wechat.model.data.user;
/**
* 用户增量数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class UserSummary implements Serializable {
private static final long serialVersionUID = -6612438038581745613L;
/**
* 日期: yyyy-MM-dd
*/
@JsonProperty("ref_date")
private String date;
/**
* 用户的渠道
* @see UserSource
*/
@JsonProperty("user_source") | // Path: src/main/java/me/hao0/wechat/serializer/UserSourceDeserializer.java
// public class UserSourceDeserializer extends JsonDeserializer<UserSource> {
//
// @Override
// public UserSource deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return UserSource.from(parser.getIntValue());
// }
// }
// Path: src/main/java/me/hao0/wechat/model/data/user/UserSummary.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.UserSourceDeserializer;
import java.io.Serializable;
package me.hao0.wechat.model.data.user;
/**
* 用户增量数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class UserSummary implements Serializable {
private static final long serialVersionUID = -6612438038581745613L;
/**
* 日期: yyyy-MM-dd
*/
@JsonProperty("ref_date")
private String date;
/**
* 用户的渠道
* @see UserSource
*/
@JsonProperty("user_source") | @JsonDeserialize(using = UserSourceDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/material/Material.java | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date; | package me.hao0.wechat.model.material;
/**
* 素材基类
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 12/11/15
*/
public abstract class Material implements Serializable {
@JsonProperty("media_id")
protected String mediaId;
@JsonProperty("update_time") | // Path: src/main/java/me/hao0/wechat/serializer/DateDeserializer.java
// public class DateDeserializer extends JsonDeserializer<Date> {
//
// @Override
// public Date deserialize(JsonParser parser, DeserializationContext context)
// throws IOException {
// return new Date(parser.getIntValue() * 1000L);
// }
// }
// Path: src/main/java/me/hao0/wechat/model/material/Material.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.DateDeserializer;
import java.io.Serializable;
import java.util.Date;
package me.hao0.wechat.model.material;
/**
* 素材基类
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 12/11/15
*/
public abstract class Material implements Serializable {
@JsonProperty("media_id")
protected String mediaId;
@JsonProperty("update_time") | @JsonDeserialize(using = DateDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/data/article/ArticleSummaryHour.java | // Path: src/main/java/me/hao0/wechat/serializer/ArticleSourceDeserializer.java
// public class ArticleSourceDeserializer extends JsonDeserializer<ArticleSource> {
//
// @Override
// public ArticleSource deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return ArticleSource.from(parser.getIntValue());
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.ArticleSourceDeserializer; | package me.hao0.wechat.model.data.article;
/**
* 图文统计分时数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class ArticleSummaryHour extends CommonSummary {
private static final long serialVersionUID = -5668724641461918373L;
/**
* 用户渠道
*/
@JsonProperty("user_source") | // Path: src/main/java/me/hao0/wechat/serializer/ArticleSourceDeserializer.java
// public class ArticleSourceDeserializer extends JsonDeserializer<ArticleSource> {
//
// @Override
// public ArticleSource deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// return ArticleSource.from(parser.getIntValue());
// }
// }
// Path: src/main/java/me/hao0/wechat/model/data/article/ArticleSummaryHour.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import me.hao0.wechat.serializer.ArticleSourceDeserializer;
package me.hao0.wechat.model.data.article;
/**
* 图文统计分时数据
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 20/11/15
*/
public class ArticleSummaryHour extends CommonSummary {
private static final long serialVersionUID = -5668724641461918373L;
/**
* 用户渠道
*/
@JsonProperty("user_source") | @JsonDeserialize(using = ArticleSourceDeserializer.class) |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/WechatBuilder.java | // Path: src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java
// public interface AccessTokenLoader {
//
// /**
// * 获取accessToken
// * @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
// */
// String get();
//
// /**
// * 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
// * @param token 从微信服务器获取AccessToken
// */
// void refresh(AccessToken token);
// }
//
// Path: src/main/java/me/hao0/wechat/loader/TicketLoader.java
// public interface TicketLoader {
//
// /**
// * 获取Ticket
// * @param type ticket类型
// * @see me.hao0.wechat.model.js.TicketType
// * @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
// */
// String get(TicketType type);
//
// /**
// * 刷新Ticket
// * @param ticket 最新获取到的Ticket
// */
// void refresh(Ticket ticket);
// }
| import me.hao0.wechat.loader.AccessTokenLoader;
import me.hao0.wechat.loader.TicketLoader;
import java.util.concurrent.ExecutorService;
import static me.hao0.common.util.Preconditions.*; | package me.hao0.wechat.core;
/**
* 微信组件库配置构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 14/11/15
* @since 1.4.0
*/
public final class WechatBuilder {
private Wechat wechat;
/**
* 创建一个WechatBuilder
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return a builder
*/
public static WechatBuilder newBuilder(String appId, String appSecret){
checkNotNullAndEmpty(appId, "appId");
checkNotNullAndEmpty(appSecret, "appSecret");
WechatBuilder builder = new WechatBuilder();
builder.wechat = new Wechat(appId, appSecret);
return builder;
}
/**
* 配置微信APP令牌(Token)
* @param token 微信APP令牌(Token)
* @return this
*/
public WechatBuilder token(String token){
checkNotNullAndEmpty(token, "token");
wechat.appToken = token;
return this;
}
/**
* 配置加密消息的Key
* @param msgKey 加密消息的Key
* @return this
*/
public WechatBuilder msgKey(String msgKey){
checkNotNullAndEmpty(msgKey, "msgKey");
wechat.msgKey = msgKey;
return this;
}
/**
* 配置accessToken加载器
* @param accessTokenLoader accessToken加载器
* @return return this
*/ | // Path: src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java
// public interface AccessTokenLoader {
//
// /**
// * 获取accessToken
// * @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
// */
// String get();
//
// /**
// * 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
// * @param token 从微信服务器获取AccessToken
// */
// void refresh(AccessToken token);
// }
//
// Path: src/main/java/me/hao0/wechat/loader/TicketLoader.java
// public interface TicketLoader {
//
// /**
// * 获取Ticket
// * @param type ticket类型
// * @see me.hao0.wechat.model.js.TicketType
// * @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
// */
// String get(TicketType type);
//
// /**
// * 刷新Ticket
// * @param ticket 最新获取到的Ticket
// */
// void refresh(Ticket ticket);
// }
// Path: src/main/java/me/hao0/wechat/core/WechatBuilder.java
import me.hao0.wechat.loader.AccessTokenLoader;
import me.hao0.wechat.loader.TicketLoader;
import java.util.concurrent.ExecutorService;
import static me.hao0.common.util.Preconditions.*;
package me.hao0.wechat.core;
/**
* 微信组件库配置构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 14/11/15
* @since 1.4.0
*/
public final class WechatBuilder {
private Wechat wechat;
/**
* 创建一个WechatBuilder
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return a builder
*/
public static WechatBuilder newBuilder(String appId, String appSecret){
checkNotNullAndEmpty(appId, "appId");
checkNotNullAndEmpty(appSecret, "appSecret");
WechatBuilder builder = new WechatBuilder();
builder.wechat = new Wechat(appId, appSecret);
return builder;
}
/**
* 配置微信APP令牌(Token)
* @param token 微信APP令牌(Token)
* @return this
*/
public WechatBuilder token(String token){
checkNotNullAndEmpty(token, "token");
wechat.appToken = token;
return this;
}
/**
* 配置加密消息的Key
* @param msgKey 加密消息的Key
* @return this
*/
public WechatBuilder msgKey(String msgKey){
checkNotNullAndEmpty(msgKey, "msgKey");
wechat.msgKey = msgKey;
return this;
}
/**
* 配置accessToken加载器
* @param accessTokenLoader accessToken加载器
* @return return this
*/ | public WechatBuilder accessTokenLoader(AccessTokenLoader accessTokenLoader){ |
ihaolin/wechat | src/main/java/me/hao0/wechat/core/WechatBuilder.java | // Path: src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java
// public interface AccessTokenLoader {
//
// /**
// * 获取accessToken
// * @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
// */
// String get();
//
// /**
// * 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
// * @param token 从微信服务器获取AccessToken
// */
// void refresh(AccessToken token);
// }
//
// Path: src/main/java/me/hao0/wechat/loader/TicketLoader.java
// public interface TicketLoader {
//
// /**
// * 获取Ticket
// * @param type ticket类型
// * @see me.hao0.wechat.model.js.TicketType
// * @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
// */
// String get(TicketType type);
//
// /**
// * 刷新Ticket
// * @param ticket 最新获取到的Ticket
// */
// void refresh(Ticket ticket);
// }
| import me.hao0.wechat.loader.AccessTokenLoader;
import me.hao0.wechat.loader.TicketLoader;
import java.util.concurrent.ExecutorService;
import static me.hao0.common.util.Preconditions.*; | package me.hao0.wechat.core;
/**
* 微信组件库配置构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 14/11/15
* @since 1.4.0
*/
public final class WechatBuilder {
private Wechat wechat;
/**
* 创建一个WechatBuilder
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return a builder
*/
public static WechatBuilder newBuilder(String appId, String appSecret){
checkNotNullAndEmpty(appId, "appId");
checkNotNullAndEmpty(appSecret, "appSecret");
WechatBuilder builder = new WechatBuilder();
builder.wechat = new Wechat(appId, appSecret);
return builder;
}
/**
* 配置微信APP令牌(Token)
* @param token 微信APP令牌(Token)
* @return this
*/
public WechatBuilder token(String token){
checkNotNullAndEmpty(token, "token");
wechat.appToken = token;
return this;
}
/**
* 配置加密消息的Key
* @param msgKey 加密消息的Key
* @return this
*/
public WechatBuilder msgKey(String msgKey){
checkNotNullAndEmpty(msgKey, "msgKey");
wechat.msgKey = msgKey;
return this;
}
/**
* 配置accessToken加载器
* @param accessTokenLoader accessToken加载器
* @return return this
*/
public WechatBuilder accessTokenLoader(AccessTokenLoader accessTokenLoader){
checkNotNull(accessTokenLoader, "accessTokenLoader can't be null");
wechat.tokenLoader = accessTokenLoader;
return this;
}
/**
* 配置ticket加载器
* @param ticketLoader ticket加载器
* @return this
*/ | // Path: src/main/java/me/hao0/wechat/loader/AccessTokenLoader.java
// public interface AccessTokenLoader {
//
// /**
// * 获取accessToken
// * @return accessToken,""或NULL会重新从微信服务器获取,并进行refresh
// */
// String get();
//
// /**
// * 刷新accessToken,实现时需要保存一段时间,以免频繁从微信服务器获取
// * @param token 从微信服务器获取AccessToken
// */
// void refresh(AccessToken token);
// }
//
// Path: src/main/java/me/hao0/wechat/loader/TicketLoader.java
// public interface TicketLoader {
//
// /**
// * 获取Ticket
// * @param type ticket类型
// * @see me.hao0.wechat.model.js.TicketType
// * @return 有效的ticket,若返回""或null,则触发重新从微信请求Ticket的方法refresh
// */
// String get(TicketType type);
//
// /**
// * 刷新Ticket
// * @param ticket 最新获取到的Ticket
// */
// void refresh(Ticket ticket);
// }
// Path: src/main/java/me/hao0/wechat/core/WechatBuilder.java
import me.hao0.wechat.loader.AccessTokenLoader;
import me.hao0.wechat.loader.TicketLoader;
import java.util.concurrent.ExecutorService;
import static me.hao0.common.util.Preconditions.*;
package me.hao0.wechat.core;
/**
* 微信组件库配置构建器
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 14/11/15
* @since 1.4.0
*/
public final class WechatBuilder {
private Wechat wechat;
/**
* 创建一个WechatBuilder
* @param appId 微信appId
* @param appSecret 微信appSecret
* @return a builder
*/
public static WechatBuilder newBuilder(String appId, String appSecret){
checkNotNullAndEmpty(appId, "appId");
checkNotNullAndEmpty(appSecret, "appSecret");
WechatBuilder builder = new WechatBuilder();
builder.wechat = new Wechat(appId, appSecret);
return builder;
}
/**
* 配置微信APP令牌(Token)
* @param token 微信APP令牌(Token)
* @return this
*/
public WechatBuilder token(String token){
checkNotNullAndEmpty(token, "token");
wechat.appToken = token;
return this;
}
/**
* 配置加密消息的Key
* @param msgKey 加密消息的Key
* @return this
*/
public WechatBuilder msgKey(String msgKey){
checkNotNullAndEmpty(msgKey, "msgKey");
wechat.msgKey = msgKey;
return this;
}
/**
* 配置accessToken加载器
* @param accessTokenLoader accessToken加载器
* @return return this
*/
public WechatBuilder accessTokenLoader(AccessTokenLoader accessTokenLoader){
checkNotNull(accessTokenLoader, "accessTokenLoader can't be null");
wechat.tokenLoader = accessTokenLoader;
return this;
}
/**
* 配置ticket加载器
* @param ticketLoader ticket加载器
* @return this
*/ | public WechatBuilder ticketLoader(TicketLoader ticketLoader){ |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/msg/RecvVoiceMessage.java | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
| import me.hao0.wechat.model.message.receive.RecvMessageType; | package me.hao0.wechat.model.message.receive.msg;
/**
* 语音消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvVoiceMessage extends RecvMsg {
private static final long serialVersionUID = 4578361001225765322L;
/**
* 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
/**
* 语音格式,如amr,speex等
*/
private String format;
/**
* 语音识别结果,使用UTF8编码
*/
private String recognition;
public RecvVoiceMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getRecognition() {
return recognition;
}
public void setRecognition(String recognition) {
this.recognition = recognition;
}
@Override
public String getMsgType() { | // Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
// public enum RecvMessageType {
//
// TEXT("text", "文本消息"),
// IMAGE("image", "图片消息"),
// VOICE("voice", "语音消息"),
// VIDEO("video", "视频消息"),
// SHORT_VIDEO("shortvideo", "小视频消息"),
// LOCATION("location", "地理位置信息"),
// LINK("link", "链接信息"),
// /**
// * 接收到微信服务器的事件消息:
// * @see me.hao0.wechat.model.message.receive.event.RecvEventType
// */
// EVENT("event", "事件消息");
//
// private String value;
//
// private String desc;
//
// private RecvMessageType(String value, String desc){
// this.value = value;
// this.desc = desc;
// }
//
// public String value(){
// return value;
// }
//
// public String desc(){
// return desc;
// }
//
// public static RecvMessageType from(String type){
// for (RecvMessageType t : RecvMessageType.values()){
// if (Objects.equals(t.value(), type)){
// return t;
// }
// }
// throw new EventException("unknown message type");
// }
//
// @Override
// public String toString() {
// return "RecvMessageType{" +
// "value='" + value + '\'' +
// ", desc='" + desc + '\'' +
// '}';
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/msg/RecvVoiceMessage.java
import me.hao0.wechat.model.message.receive.RecvMessageType;
package me.hao0.wechat.model.message.receive.msg;
/**
* 语音消息
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 9/11/15
*/
public class RecvVoiceMessage extends RecvMsg {
private static final long serialVersionUID = 4578361001225765322L;
/**
* 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
*/
private String mediaId;
/**
* 语音格式,如amr,speex等
*/
private String format;
/**
* 语音识别结果,使用UTF8编码
*/
private String recognition;
public RecvVoiceMessage(RecvMsg m){
super(m);
this.msgId = m.msgId;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getRecognition() {
return recognition;
}
public void setRecognition(String recognition) {
this.recognition = recognition;
}
@Override
public String getMsgType() { | return RecvMessageType.VOICE.value(); |
ihaolin/wechat | src/test/java/me/hao0/wechat/XmlWritersTest.java | // Path: src/main/java/me/hao0/wechat/utils/XmlWriters.java
// public class XmlWriters {
//
// List<E> es = new ArrayList<>();
//
// private XmlWriters(){}
//
// public static XmlWriters create(){
// return new XmlWriters();
// }
//
// public XmlWriters element(String name, String text){
// E e = new TextE(name, text);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String name, Number number){
// E e = new NumberE(name, number);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String parentName, String childName, String childText){
// return element(parentName, new TextE(childName, childText));
// }
//
// public XmlWriters element(String parentName, String childName, Number childNumber){
// return element(parentName, new NumberE(childName, childNumber));
// }
//
// /**
// * 构建包含多个子元素的元素
// * @param parentName 父元素标签名
// * @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
// * @return this
// */
// public XmlWriters element(String parentName, Object... childPairs){
// if (childPairs.length % 2 != 0){
// throw new XmlException("var args's length must % 2 = 0");
// }
// E parent = new TextE(parentName, null);
// List<E> children = new ArrayList<>();
// E child;
// for (int i=0; i<childPairs.length ; i=i+2){
// if (childPairs[i+1] instanceof Number){
// child = new NumberE((String)childPairs[i], (Serializable)childPairs[i+1]);
// } else {
// child = new TextE((String)childPairs[i], (Serializable)childPairs[i+1]);
// }
// children.add(child);
// }
// parent.children = children;
// es.add(parent);
// return this;
// }
//
// public XmlWriters element(String parentName, E child){
// E e = new TextE(parentName, null);
// e.children = Arrays.asList(child);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String parentName, List<E> children){
// E e = new TextE(parentName, null);
// e.children = children;
// es.add(e);
// return this;
// }
//
// /**
// * 构建包含多个子元素的元素
// * @param parentName 父元素标签名
// * @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
// * @return an element
// */
// public E newElement(String parentName, Object... childPairs){
// E parent = new TextE(parentName, null);
// List<E> children = new ArrayList<>();
// E child;
// for (int i=0; i<childPairs.length ; i=i+2){
// if (childPairs[i+1] instanceof Number){
// child = new NumberE((String)childPairs[i], (Serializable)childPairs[i+1]);
// } else {
// child = new TextE((String)childPairs[i], (Serializable)childPairs[i+1]);
// }
// children.add(child);
// }
// parent.children = children;
// return parent;
// }
//
// public String build(){
// return buildElements();
// }
//
// private String buildElements() {
//
// StringBuilder xml = new StringBuilder();
//
// xml.append("<xml>");
//
// if (es != null && es.size() > 0){
// for (E e : es){
// xml.append(e.render());
// }
// }
//
// xml.append("</xml>");
//
// return xml.toString();
// }
//
// public static abstract class E {
//
// String name;
//
// Object text;
//
// List<E> children;
//
// public E(String name, Object text) {
// this.name = name;
// this.text = text;
// }
//
// protected abstract String render();
// }
//
// public static final class TextE extends E {
//
// public TextE(String name, Serializable content) {
// super(name, content);
// }
//
// @Override
// protected String render() {
// StringBuilder content = new StringBuilder();
// content.append("<").append(name).append(">");
//
// if (text != null){
// content.append("<![CDATA[").append(text).append("]]>");
// }
//
// if (children != null && children.size() > 0){
// for (E child : children){
// content.append(child.render());
// }
// }
//
// content.append("</").append(name).append(">");
// return content.toString();
// }
// }
//
// public static final class NumberE extends E {
//
// public NumberE(String name, Serializable content) {
// super(name, content);
// }
//
// @Override
// protected String render() {
// StringBuilder content = new StringBuilder();
// content.append("<").append(name).append(">")
// .append(text)
// .append("</").append(name).append(">");
// return content.toString();
// }
// }
// }
| import me.hao0.wechat.utils.XmlWriters;
import org.junit.Test;
import static org.junit.Assert.*; | package me.hao0.wechat;
/**
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 6/11/15
*/
public class XmlWritersTest {
@Test
public void testOneLevel(){ | // Path: src/main/java/me/hao0/wechat/utils/XmlWriters.java
// public class XmlWriters {
//
// List<E> es = new ArrayList<>();
//
// private XmlWriters(){}
//
// public static XmlWriters create(){
// return new XmlWriters();
// }
//
// public XmlWriters element(String name, String text){
// E e = new TextE(name, text);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String name, Number number){
// E e = new NumberE(name, number);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String parentName, String childName, String childText){
// return element(parentName, new TextE(childName, childText));
// }
//
// public XmlWriters element(String parentName, String childName, Number childNumber){
// return element(parentName, new NumberE(childName, childNumber));
// }
//
// /**
// * 构建包含多个子元素的元素
// * @param parentName 父元素标签名
// * @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
// * @return this
// */
// public XmlWriters element(String parentName, Object... childPairs){
// if (childPairs.length % 2 != 0){
// throw new XmlException("var args's length must % 2 = 0");
// }
// E parent = new TextE(parentName, null);
// List<E> children = new ArrayList<>();
// E child;
// for (int i=0; i<childPairs.length ; i=i+2){
// if (childPairs[i+1] instanceof Number){
// child = new NumberE((String)childPairs[i], (Serializable)childPairs[i+1]);
// } else {
// child = new TextE((String)childPairs[i], (Serializable)childPairs[i+1]);
// }
// children.add(child);
// }
// parent.children = children;
// es.add(parent);
// return this;
// }
//
// public XmlWriters element(String parentName, E child){
// E e = new TextE(parentName, null);
// e.children = Arrays.asList(child);
// es.add(e);
// return this;
// }
//
// public XmlWriters element(String parentName, List<E> children){
// E e = new TextE(parentName, null);
// e.children = children;
// es.add(e);
// return this;
// }
//
// /**
// * 构建包含多个子元素的元素
// * @param parentName 父元素标签名
// * @param childPairs childName1, childValue1, childName2, childValu2, ...,长度必读为2的倍数
// * @return an element
// */
// public E newElement(String parentName, Object... childPairs){
// E parent = new TextE(parentName, null);
// List<E> children = new ArrayList<>();
// E child;
// for (int i=0; i<childPairs.length ; i=i+2){
// if (childPairs[i+1] instanceof Number){
// child = new NumberE((String)childPairs[i], (Serializable)childPairs[i+1]);
// } else {
// child = new TextE((String)childPairs[i], (Serializable)childPairs[i+1]);
// }
// children.add(child);
// }
// parent.children = children;
// return parent;
// }
//
// public String build(){
// return buildElements();
// }
//
// private String buildElements() {
//
// StringBuilder xml = new StringBuilder();
//
// xml.append("<xml>");
//
// if (es != null && es.size() > 0){
// for (E e : es){
// xml.append(e.render());
// }
// }
//
// xml.append("</xml>");
//
// return xml.toString();
// }
//
// public static abstract class E {
//
// String name;
//
// Object text;
//
// List<E> children;
//
// public E(String name, Object text) {
// this.name = name;
// this.text = text;
// }
//
// protected abstract String render();
// }
//
// public static final class TextE extends E {
//
// public TextE(String name, Serializable content) {
// super(name, content);
// }
//
// @Override
// protected String render() {
// StringBuilder content = new StringBuilder();
// content.append("<").append(name).append(">");
//
// if (text != null){
// content.append("<![CDATA[").append(text).append("]]>");
// }
//
// if (children != null && children.size() > 0){
// for (E child : children){
// content.append(child.render());
// }
// }
//
// content.append("</").append(name).append(">");
// return content.toString();
// }
// }
//
// public static final class NumberE extends E {
//
// public NumberE(String name, Serializable content) {
// super(name, content);
// }
//
// @Override
// protected String render() {
// StringBuilder content = new StringBuilder();
// content.append("<").append(name).append(">")
// .append(text)
// .append("</").append(name).append(">");
// return content.toString();
// }
// }
// }
// Path: src/test/java/me/hao0/wechat/XmlWritersTest.java
import me.hao0.wechat.utils.XmlWriters;
import org.junit.Test;
import static org.junit.Assert.*;
package me.hao0.wechat;
/**
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 6/11/15
*/
public class XmlWritersTest {
@Test
public void testOneLevel(){ | XmlWriters xmlWriters = XmlWriters.create(); |
ihaolin/wechat | src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java | // Path: src/main/java/me/hao0/wechat/exception/EventException.java
// public class EventException extends RuntimeException {
//
// public EventException() {
// super();
// }
//
// public EventException(String message) {
// super(message);
// }
//
// public EventException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EventException(Throwable cause) {
// super(cause);
// }
//
// protected EventException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
| import me.hao0.wechat.exception.EventException;
import java.util.Objects; | package me.hao0.wechat.model.message.receive;
/**
* 接收微信服务器的消息类型
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 8/11/15
*/
public enum RecvMessageType {
TEXT("text", "文本消息"),
IMAGE("image", "图片消息"),
VOICE("voice", "语音消息"),
VIDEO("video", "视频消息"),
SHORT_VIDEO("shortvideo", "小视频消息"),
LOCATION("location", "地理位置信息"),
LINK("link", "链接信息"),
/**
* 接收到微信服务器的事件消息:
* @see me.hao0.wechat.model.message.receive.event.RecvEventType
*/
EVENT("event", "事件消息");
private String value;
private String desc;
private RecvMessageType(String value, String desc){
this.value = value;
this.desc = desc;
}
public String value(){
return value;
}
public String desc(){
return desc;
}
public static RecvMessageType from(String type){
for (RecvMessageType t : RecvMessageType.values()){
if (Objects.equals(t.value(), type)){
return t;
}
} | // Path: src/main/java/me/hao0/wechat/exception/EventException.java
// public class EventException extends RuntimeException {
//
// public EventException() {
// super();
// }
//
// public EventException(String message) {
// super(message);
// }
//
// public EventException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EventException(Throwable cause) {
// super(cause);
// }
//
// protected EventException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
// Path: src/main/java/me/hao0/wechat/model/message/receive/RecvMessageType.java
import me.hao0.wechat.exception.EventException;
import java.util.Objects;
package me.hao0.wechat.model.message.receive;
/**
* 接收微信服务器的消息类型
* Author: haolin
* Email: haolin.h0@gmail.com
* Date: 8/11/15
*/
public enum RecvMessageType {
TEXT("text", "文本消息"),
IMAGE("image", "图片消息"),
VOICE("voice", "语音消息"),
VIDEO("video", "视频消息"),
SHORT_VIDEO("shortvideo", "小视频消息"),
LOCATION("location", "地理位置信息"),
LINK("link", "链接信息"),
/**
* 接收到微信服务器的事件消息:
* @see me.hao0.wechat.model.message.receive.event.RecvEventType
*/
EVENT("event", "事件消息");
private String value;
private String desc;
private RecvMessageType(String value, String desc){
this.value = value;
this.desc = desc;
}
public String value(){
return value;
}
public String desc(){
return desc;
}
public static RecvMessageType from(String type){
for (RecvMessageType t : RecvMessageType.values()){
if (Objects.equals(t.value(), type)){
return t;
}
} | throw new EventException("unknown message type"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.